Setter Injection with Dependent Object Example in Spring

Like Constructor Injection, we can inject the dependency of another bean using setters. In such case, we use property element. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object.

Address.java

This class contains four properties, setters and getters and toString() strategy.


package com.javatportal;

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

//getters and setters

public String toString(){
	return addressLine1+" "+city+" "+state+" "+country;
}
Employee.java

It contains three properties id, name and address(dependent object) , setters and getters with displayInfo() method.

package com.javatportal;

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

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.javatportal.Address">
<property name="addressLine1" value="101,Noida"></property>
<property name="city" value="Noida"></property>
<property name="state" value="UP"></property>
<property name="country" value="India"></property>
</bean>

<bean id="obj" class="com.javatportal.Employee">
<property name="id" value="1"></property>
<property name="name" value="Mukesh Singh"></property>
<property name="address" ref="address1"></property>
</bean>

</beans>
Test.java

This class gets the bean from the applicationContext.xml document and calls the displayInfo() system.

package com.javatportal;

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();
	
}
}