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>
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"
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 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=""
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