Thursday, February 7, 2019

How to Inject Null And Empty String Values in Spring

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 in Spring 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 then the configuration is as given below-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name" value="" />        
</bean> 

If passed as property then the configuration is as given below-

<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 in Spring 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 in your Spring configuration.

<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!

>>>Return to Spring Tutorial Page


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-

  1. Spring Bean Life Cycle
  2. Autodiscovery of Bean Using component-scan in Spring
  3. How to Read Properties File in Spring Framework
  4. Using Spring Profiles to Switch Environment
  5. How HashMap Internally Works in Java
  6. Reflection in Java
  7. Initializer Block in Java
  8. What is HDFS