Different ways of Injecting Value into Bean Properties in Spring

In some of my previous post, you have seen the following way of inject value into bean properties.

<bean id="employee" class="com.kruders.bean.Employee">
    <property name="name">
        <value>Puneet</value>
    </property>
</bean>

However, there are several options available for you to limit the amount of XML you have to write to configure your components.

1. XML-based configuration metadata shortcuts

The <property/> element supports a ‘value’ attribute which may be used instead of embedding a full <value/> element.

<bean id="employee" class="com.kruders.bean.Employee">
    <property name="name" value="Puneet" />
</bean>

2. The p-namespace

The second option you have to limit the amount of XML you have to write to configure your components is to use the special “p-namespace”. Spring 2.0 and later features support for extensible configuration formats using namespaces. Those namespaces are all based on an XML Schema definition.

<bean id="employee" class="com.kruders.bean.Employee" p:name="Puneet">
</bean>

No comments yet.

Leave a Reply