How to Inject Null and Empty Values in Spring

By Arvind Rai, 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> 
Find the code snippet to inject empty value.
<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> 
Test.java
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;
	}
}
 
SpringTest.java
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.");
	     }
	}
} 

Reference

Null and Empty String Values
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us