Inject Null Values in Spring With Example

Inject Null Values in Spring With Example

In Spring we can inject null values for spring bean properties by using <null/> tag. see the structure below

<bean id="demoBean" class="DemoBean">
<property name="message"><null/>
</property>

</bean>

Tools Used In This Article

  • Spring 4.3.2
  • Maven 4.0.0
  • JDK 1.6

1.Create Maven Project like below

2.writing spring Bean


package com.mypractice;

public class DemoBean {
private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

@Override
public String toString() {
return "DemoBean [message=" + message + "]";
}


}


3.Here is spring configuration file (applicationContext.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-4.3.xsd">
<bean id="demoBean" class="com.mypractice.DemoBean">

<property name="message"><null/>
</property>


</bean>

</beans>

4.create Test class And Run the code


package com.mypractice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DemoBean demoBean = (DemoBean)context.getBean("demoBean");
System.out.println(demoBean.toString());

}

}


output:


Jan 24, 2017 10:52:32 AM INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1afd2e1f: startup date [Tue Jan 24 11:54:34 IST 2017]; root of context hierarchy
Jan 24, 2017 11:54:34 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
DemoBean [message=null]

-->