Saturday, April 23, 2022

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. Spring Expression Language (SpEL) With Examples
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Spring Bean Life Cycle
  2. Spring Component Scan to Automatically Discover Beans
  3. How to Read Properties File in Spring Framework
  4. Spring Profiles With Examples
  5. How HashMap Internally Works in Java
  6. Java Reflection API Tutorial
  7. Initializer Block in Java
  8. What is Hadoop Distributed File System (HDFS)