logo

Spring Setter Injection With Dependent Object


Show

We can also inject the dependency between the objects by the use of Dependent objects in the Setter injection in Spring, just like in the Constructor injection. In this example, we will use the property element. We also observe that there is a condition that says Employee HAS-A Address. Here, it is obvious that the Address class object is the dependent object.

Let's study the Address class first:

Address.Java

This class includes four properties, setters and getters and the toString() method.

package com.intellinuts;  

public class Address {  
private String addressLine1,city,state,country;  

//getters and setters  

public String toString(){  
    return addressLine1+" "+city+" "+state+" "+country;  

}  

Employee.Java

This class contains id, name, and address(dependent object) as the three properties as well as setters and getters with the displayInfo() method to print the result values.

package com.intellinuts;  

public class Employee {  
private int id;  
private String name;  
private Address address;  

//setters and getters  

void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println(address);  
}  
}  

ApplicationContext.xml

On this page, the ref attribute of property elements is used to define the reference of another bean.

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="address1" class="com.intellinuts.Address">  
<property name="addressLine1" value="51,Lohianagar"></property>  
<property name="city" value="Ghaziabad"></property>  
<property name="state" value="UP"></property>  
<property name="country" value="India"></property>  
</bean>  

<bean id="obj" class="com.intellinuts.Employee">  
<property name="id" value="1"></property>  
<property name="name" value="Sachin Yadav"></property>  
<property name="address" ref="address1"></property>  
</bean>  

</beans>

Test.Java

This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.

package com.intellinuts;  

import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  

public class Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  

    Employee e=(Employee)factory.getBean("obj");  
    e.displayInfo();  
}  
}