Search This Blog

Friday 9 March 2012

Injecting Null

In the last posts we saw Springs ability to inject collections - both simple value types and complex object types. But just because Spring allows us to configure objects does not mean we have to always configure them. For e.g. there could be a Singer class that uses constructor injection to wire its "song" property. But what do you do if you don't have a song ?
You need to pass some value to the constructor so as to ensure the singer bean is created.
If you were writing straight forward 'spring-absent' code, you would simple pass a null value to the constructor.
Singer singer = new Singer(null);
Can we do the same in Spring ? Yes, obviously we can, else I wouldn't be typing this here! Spring allows us to wire properties with the value null.
<bean name ="songlessSinger" class="com.performer.Singer">
    <property name="song">
        <null />
    </property>
</bean>
For the song attribute we have passed the value null. If we were to test this bean
public static void main(String[] args) {
    XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
    IPerformer songlessSinger = (IPerformer) beanFactory.getBean("songlessSinger");
    songlessSinger.perform();
}
The output indicates the null value:
Creating a singer instance com.performer.Singer@1f4689e
singing null....
The null element is also available in case of collections. Consider the <list> element below:
<property name="credits">
    <list>        
        <null/>
        <value>Yank Mildow</value>
        <value>Ryan Star</value>
    </list>
</property>
Same goes for the <map> element:
<property name="winners">
    <map>
        <entry key="First Prize"><null></null></entry>
        <entry key ="Second Prize" value="Miss Mana"></entry>
    </map>
</property>
I tried to insert a null value for a properties, but that is not supported.
<property name="dressDetails">
    <props>
        <prop key="DressCode"><null/></prop>
        <prop key="Tie">Optional</prop>
        <prop key="Glasses">Tinted</prop>
    </props>
</property>
It gives the validation exception
org.xml.sax.SAXParseException: cvc-complex-type.2.4.d: Invalid content was found starting with element 'null'. No child element is expected at this point.

1 comment: