Constructor Injection with Dependent Object in Spring

Constructor Injection with Dependent Object In the event that there is HAS-A relationship between the classes, we make the case of ward item (contained article) first then pass it as a contention of the fundamental class constructor. Here, our situation is Employee HAS-An Address.

The Address class item will be termed as the subordinate article. The Dependency Injection is an outline design that evacuates the reliance of the projects. In such case we give the data from the outer source, for example, XML document. It makes our code inexactly coupled and less demanding for testing.

This class contains three properties, one constructor and toString() method to return the values of these object.

package com.javatportal;

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

public Address(String city, String state, String country) {
	super(); = city;
	this.state = state; = country;

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

It contains three properties id, name and address(dependent object) ,two constructors and show() method to show the records of the current object including the depedent object.

package com.javatportal;

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

public Employee() {System.out.println("def cons");}

public Employee(int id, String name, Address address) {
	super(); = id; = name;
	this.address = address;

void show(){
	System.out.println(id+" "+name);



The ref attribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument.

<?xml version="1.0" encoding="UTF-8"?>

<bean id="a1" class="com.javatportal.Address">
<constructor-arg value="Noida"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>

<bean id="e" class="com.javatportal.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Mithilesh"></constructor-arg>
<ref bean="a1"/>


This class gets the bean from the applicationContext.xml file and calls the show method.

package com.javatportal;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

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