This post shows how you can inject null or empty String as a value for any property in Spring framework.
Injecting empty string
If you are trying to inject an empty string as a value for any property then you can just pass “” as a value for that property.
As example
If you have an Employee class with name as field. Then you can use “” for name property.
If passed as a constructor argument -
<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
<constructor-arg name="name" value="" />
</bean>
If passed as property -
<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
<property name="name" value=""/>
</bean>
Injecting null
If you need to inject null value for any field then use the special <null/> element for it, don’t use value=”null”because that will pass "null" as a String value.
So don’t do this -
<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
<constructor-arg name="name" value="null" />
</bean>
Use <null/> element instead.
<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
<constructor-arg name="name">
<null/>
</constructor-arg>
</bean>
If passed as setter property -
<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
<property name="name"><null/></property>
</bean>
That's all for this topic How to Inject Null And Empty String Values in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -