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.


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


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


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


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(
		Employee e = (Employee) context.getBean("employee");
Employee ID: 101 Name: Mukesh
City is Chennai State is  Tamilnadu and Country is India

Previous Next Article
comments powered by Disqus