How to Inject Null and Empty Values in Spring
November 04, 2021
In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null>
element.
Find the code snippet to inject null value.
<property name="a"><null/></property>
<property name="b" value=""/>
Example
app-context.xml<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="test" class="com.concretepage.Test"> <property name="a"> <null/></property> <property name="b" value=""/> </bean> </beans>
package com.concretepage; public class Test { private Integer a; private String b; public Integer getA() { return a; } public void setA(Integer a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } }
package com.concretepage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml"); Test test=(Test)context.getBean("test"); if(test.getA()==null){ System.out.println("null value."); } if("".equals(test.getB())){ System.out.println("Empty value."); } } }