Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

How to Inject Null And Empty String Values in Spring

$
0
0

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

  1. Dependency Injection Using factory-method in Spring
  2. Wiring Collections in Spring
  3. Run Time Injection Using Spring Expression Language(SpEL)
  4. How to Inject Prototype Scoped Bean in Singleton Bean
  5. Lazy Initializing Spring Beans

You may also like -

>>>Go to Spring Tutorial Page


Viewing all articles
Browse latest Browse all 938

Trending Articles