Search This Blog

Thursday 1 March 2012

The p namespace

<bean id ="band" class ="com.performer.Band">
    <property name="musician" ref="musician"></property>
    <property name="singer" ref="singer"></property>
</bean>
The above XML fragment
defines a Band object with its two properties set to reference two other beans. This same amount of configuration can be written in the below shortened style:
<bean id="band" class="com.performer.Band" p:musician-ref="musician"
    p:singer-ref="shortSinger"></bean>
The single bean element was used to represent the entire band bean. This special namespace is called the p-namespace. It lets us avoid the property element, instead defining the value of the bean properties as attributes.
If the attribute is a value/literal then it can be written as p:attributename. For example the below two xml fragments are equivalent
<bean id="singer" class="com.performer.Singer">
    <property name="song" value="La La La"/>
</bean>

<bean id="singer" class="com.performer.Singer" p:song="La La La"/>
In case the property is a reference to another bean, then the format is p:attributename-ref. Thus in our first definition the singer property of band bean is injected with a reference to bean with id "shortSinger".
To add the p-namespace to our code modify the beans element to include the p namespace
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
A strange thing about the p-namespace is that, it does not refer to any XSD files which gives details of the schema. The p namespace is not defined in an XSD file. It only exists in the core of Spring.

No comments:

Post a Comment