Spring Setter injection with Dependent Object

For Dependent Object injection we have HAS-A relation scenario.In our case there is dependency of Address object in Customer class.<property> element has an attribute called ref to inject dependent object.

Customer.java

package com.startwithjava;
public class Customer {
	private int id;
	private String name;
	private Address address;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public void display(){
		System.out.println("Name:"+name+"\tCity:"+address.getCity()+"\tState"+address.getState());
	}
}

Address

package com.startwithjava;
public class Address {
	private String state;
	private String city;
	private String zipCode;
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getZipCode() {
		return zipCode;
	}
	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}
}

applicationContext.xml

This file contains the bean entry for Customer 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="address" class="com.startwithjava.Address">
   <property name="city" value="New Delhi" />
   <property name="state" value="New Delhi" />
   <property name="zipCode" value="110092" />
 </bean>
  <bean id="cust" class="com.startwithjava.Customer" autowire="byName">
   <property name="id" value="1000" />
   <property name="name" value="Ramesh" />
   <property name="address" ref="address" />
 </bean>
 </beans> 

Test.java

This file has code to get the object of cust bean from applicationContext.xml.

package com.startwithjava;
import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
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); 
    Customer c  = (Customer)factory.getBean("cust");
    c.display();
} 

Leave a Reply