Inject Empty values in Spring with Example

Spring allows empty values for properties of a spring bean.In Spring we can inject empty values in following way


<bean id="demoBean" class="DemoBean">
<property name="message" value=""></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" value=""></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 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1afd2e1f: startup date [Tue Jan 24 10:52:32 IST 2017]; root of context hierarchy
Jan 24, 2017 10:52:32 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
DemoBean [message=]