Injecting null and an empty String



This posts shows how inject null and an empty String as a value of a property of a bean.

Example.java
package example.di;

public class Example {
   
    String anEmptyString;
   
    String nullProperty;
   
    public void setAnEmptyString(String s){
        this.anEmptyString = s;
       
    }
   
    public void setNullProperty(String s){
        this.nullProperty = s;
       
    }
   
    public void display(){
        System.out.println("anEmptyString = "+ anEmptyString);
        System.out.println("nullProperty = "+ nullProperty);
    }

}

ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<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="example" class="example.di.Example">

<!-- Injecting an empty String -->
<property name="anEmptyString" value=""/>

<!-- Injecting null -->
<property name="nullProperty"><null/> </property>
</bean>


</beans>

test.java
package example.di;

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

public class test{

public static void main(String args[]){
   
    ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    Example obj = (Example) appContext.getBean("example");
   
    obj.display();
    }
}

Output
anEmptyString =
nullProperty = null


I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment