Home » Spring » Constructor Injection with Dependent Object

Constructor Injection with Dependent Object

In this example we will discuss about constructor injection with dependent object using a simple and self explanatory program.

Let us create two bean class Address and Employee. Employee class has reference of Address.

Address.java

package com.jwt.spring;
public class Address {
	private String city;
	private String state;
	private String country;
	public Address(String city, String state, String country) {
		super();
		this.city = city;
		this.state = state;
		this.country = country;
	}
	public String toString() {
		return "City is " + city + " State is  " + state + " and Country is "
				+ country;
	}
}

Employee.java

package com.jwt.spring;
public class Employee {
	private int id;
	private String name;
	private Address address;
	public Employee(int id, String name, Address address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}
	void display() {
		System.out.println("Employee ID: " + id + " Name: " + name);
		System.out.println(address.toString());
	}
}

bean.xml

Below is the code snippet to use the Set in the spring bean configuration file.As discussed the ref attribute is used to define the reference of another object.

<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="address" class="com.jwt.spring.Address">
		<constructor-arg value="Chennai"></constructor-arg>
		<constructor-arg value="Tamilnadu"></constructor-arg>
		<constructor-arg value="India"></constructor-arg>
	</bean>
	<bean id="employee" class="com.jwt.spring.Employee">
		<constructor-arg value="101" type="int"></constructor-arg>
		<constructor-arg value="Mukesh"></constructor-arg>
		<constructor-arg>
			<ref bean="address" />
		</constructor-arg>
	</bean>
</beans>

Test.java

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

package com.jwt.spring;

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

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean.xml");
		Employee e = (Employee) context.getBean("employee");
		e.display();
	}
}
Output:
Employee ID: 101 Name: Mukesh
City is Chennai State is  Tamilnadu and Country is India


Previous Next Article
comments powered by Disqus