Spring dependency injection is main feature of spring framework. To define it : let’s say we have two class Person and Address and as we know in real world person must have address. In terms of java Person will keep object of class Address as variable. If dependency injection used then Address class will be used either by constructor or setter injection.

Spring Dependency Injection: To keep object creation process outside also called Inversion of control which act as container in spring where all setting will be done and doing injection to it’s property inside it called dependency injection. Let’s see in below example:

Create class address which have address related parameter and Person class has two attribute and Address class object as below:

package com.javahonk.di.bean;

import java.io.Serializable;

public class Address implements Serializable {

    private static final long serialVersionUID = 1L;
    private String streeName;
    private String city;
    private String state;
    private String zip;    

    public Address(String streeName, String city, String state, String zip) {
		super();
		this.streeName = streeName;
		this.city = city;
		this.state = state;
		this.zip = zip;
	}
	public String getStreeName() {
        return streeName;
    }
    public void setStreeName(String streeName) {
        this.streeName = streeName;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getZip() {
        return zip;
    }
    public void setZip(String zip) {
        this.zip = zip;
    } 

}

 

Person class:

package com.javahonk.di.bean;

import java.io.Serializable;

public class Person implements Serializable{

    private static final long serialVersionUID = 1L;
    private String FirstName;
    private String LastName;
    private Address address;    

    public Person(String firstName, String lastName) {
		super();
		FirstName = firstName;
		LastName = lastName;
	}
	public String getFirstName() {
        return FirstName;
    }
    public void setFirstName(String firstName) {
        FirstName = firstName;
    }
    public String getLastName() {
        return LastName;
    }
    public void setLastName(String lastName) {
        LastName = lastName;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }

}

 

Please see below example how we do create object in java using constructor and setter and sets the it’s value:

Address address=new Address("John Rd.", "Edison", "NJ", "10038");
Person person =new Person("Mary", "Kay");
person.setAddress(address);

 

Now see same thing in spring context file application-config.xml which is also called Inversion of control to do dependency injection using constructor and setter method:

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <bean id="person" class="com.javahonk.di.bean.Person" scope="">
	   <constructor-arg type="java.lang.String" value="Mary" />
	   <constructor-arg type="java.lang.String" value="Kay" />
	   <property name="address" ref="address"></property>  
  </bean>

  <bean id="address" class="com.javahonk.di.bean.Address" scope="prototype"> 	  
	  <constructor-arg type="java.lang.String" value="John Rd." />
	  <constructor-arg type="java.lang.String" value="Edison" />
	  <constructor-arg type="java.lang.String" value="NJ" />
	  <constructor-arg type="java.lang.String" value="10038" />		  
  </bean>		  

</beans>

 

Spring use bean tag to define class with id and instantiate it. Only we need to provide what kind of injection we want to use. Below for Person class we are using constructor injection to instantiate it and for address using setter injection:

<bean id="person" class="com.javahonk.di.bean.Person" scope="">
<constructor-arg type="java.lang.String" value="Mary" />
<constructor-arg type="java.lang.String" value="Kay" />
<property name="address" ref="address"></property> 
</bean>

 

Below for Address class we are using constructor injection to instantiate:

<bean id="address" class="com.javahonk.di.bean.Address" scope="prototype"> 
<constructor-arg type="java.lang.String" value="John Rd." />
<constructor-arg type="java.lang.String" value="Edison" />
<constructor-arg type="java.lang.String" value="NJ" />
<constructor-arg type="java.lang.String" value="10038" /> 
</bean>

 

Now let’s see how it works using another java class TestDependencyInjection.java below:

package com.javahonk;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javahonk.di.bean.Address;
import com.javahonk.di.bean.Person;

public class TestDependencyInjection {

    public static void main(String[] args) {
	ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
		"spring\\application-config.xml");
	// Get person object
	Person person = applicationContext.getBean("person",
		Person.class);

	System.out.println("Constructor injection value of person:");
	System.out.println("First Name: " + person.getFirstName()
		+ "Last Name: " + person.getLastName());
	System.out.println("Setter injection value of Address:");
	System.out.println("Street: "
		+ person.getAddress().getStreeName() + "" + " City: "
		+ person.getAddress().getCity() + " State: "
		+ person.getAddress().getState() + " Zip: "
		+ person.getAddress().getZip());

	System.out
		.println("\nConstructor injection value of Address directly:");
	Address address = applicationContext.getBean(Address.class);
	System.out.println("Street: " + person.getAddress().getStreeName() + ""
		+ " City: " + address.getCity() + " State: "
		+ address.getState() + " Zip: " + address.getZip()
		+ "\n");

	applicationContext.close();

    }

}

 

Spring ClassPathXmlApplicationContext has been loaded to get the context of all the beans and get object of it at run time.

Spring Dependency Injection Spring Dependency Injection download source code: Spring Dependency Injection

Leave a Reply

Your email address will not be published. Required fields are marked *