Home  >  Spring Core

How to Inject null and empty Values in Spring

By Arvind Rai, April 11, 2013
In Spring, if we need to inject null and empty value, we can do it while creating bean and can set dependency as described below.
Null value is injected using <null/>.
<property name="a"><null/></property>
 
And empty value can be injected as
<property name="b" value=""/>
 



Using <null/> and value=""

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-3.0.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;
	}
}
 

Main Class

SpringTest
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.");
	     }
	}
} 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us