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 />
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");
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">
        <value>Yank Mildow</value>
        <value>Ryan Star</value>
Same goes for the <map> element:
<property name="winners">
        <entry key="First Prize"><null></null></entry>
        <entry key ="Second Prize" value="Miss Mana"></entry>
I tried to insert a null value for a properties, but that is not supported.
<property name="dressDetails">
        <prop key="DressCode"><null/></prop>
        <prop key="Tie">Optional</prop>
        <prop key="Glasses">Tinted</prop>
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:

  1. This comment has been removed by the author.