Dependency Injection in Spring


Dependency Injection (DI): is a way to let the framework or the container work out the complexities of service instantiation, initialization and sequencing and supplies the service references to the clients as required. In spring IOC container has the responsibility of doing DI.

 

Consider a simple example:

 

public interface Vehicle {

                 void displayData();

}

 

A FourWheeler class implements Vehicle interface.

 

public class FourWheeler implements Vehicle {

 

      private String name;

      private int purchaseValue;

      private int noOfTyres;

      public FourWheeler(){}                          // default constructor                   

public FourWheeler(String name, int purchaseValue, int noOfTyres) {

            super();

            this.name = name;

            this.purchaseValue = purchaseValue;

            this.noOfTyres = noOfTyres;

      }

      public void displayData() {

            System.out.println(” Name of vehicle is “+ name);

            System.out.println(“Purchase Value is “ +purchaseValue);

            System.out.println(“Tyres the vehicle has “ +noOfTyres);

      }

      public String getName() {

            return name;

      }

      public void setName(String name) {

            this.name = name;

      }

      public int getPurchaseValue() {

            return purchaseValue;

      }

      public void setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;

      }

      public int getNoOfTyres() {

            return noOfTyres;

      }

      public void setNoOfTyres(int noOfTyres) {

            this.noOfTyres = noOfTyres;

      }

}

 

The different ways in which the class can be instantiated using DI in spring.xml:

 

1) Setter based injection: The values of the properties of the class are set with the help of setter. Each class needs to declare the setter of the properties and their values are set from the spring configuration file.

 

 <?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans>      

       <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

            <property name=“noOfTyres”> <value>4</value>

            </property>

           

<property name=“name” value=“Honda”/>                                  

<property name=“purchaseValue” value=“900000”/>  

      </bean>

</beans>

 

In above example the setter methods are created for noOfTyres, name, purchaseValue in FourWheeler  class and the values are set using <property> <value> tag in xml file.

Note that for each property the value is set using a different syntax. All syntaxes are valid and

can be used depending on the programmer liking. In this declaration the default constructor of class is called.

 

2)  Constructor Based injection: In this case the values are set using constructor of the java class. The call to constructor is made from the xml file using <constructor-arg>.  For the above mentioned java class constructor injection will be:

 

<?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans >      

     

      <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                        <constructor-arg> index=“0” value=“Honda”/>

                        <constructor-arg type=“Integer”>

                              <value>900000</value>

                  </constructor-arg>

      </bean>    

</beans>

 

 

In the above example the values to the bean is passed using <constructor-arg>. The sequence in which the parameters are passed should match with the constructor available in the class.

 

3) Static factory method: In the less common case where the container invokes a static, factory method on a class to create the bean, the class property specifies the actual class containing the static factory method that is to be invoked to create the object (the type of the object returned from the invocation of the static factory method may be the same class or another class entirely.

 

Consider the following method present in FourWheeler class:

public static TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method has to be static. And following line of code in xml:

 

<bean id=“twoWheeler” class=“com.src.FourWheeler” factory-method=“createInstance”/>

 

After execution of the above line twoWheleler bean will represent the TwoWheeler object which is created by calling the function from FourWheeler Class. The attribute factory-method tells which method to call present in the class mentioned. This scenario could possibly use in cases where Factory pattern is required.

 

4) Instance Factory method: In this case instead of having a static method a non-static method is present to create the object.

 

Consider the following method present in FourWheeler class:

public TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method need not be static. And following line of code in xml:

 

<bean id=“parentfourWheeler” class=“com.src.FourWheeler”/>

 

<bean id=“fourWheeler” factory-bean = “parentFourWheeler” factory-method=“createInstance” />

 

Here the twoWheeler object is created from a non-static method of class FourWheeler.

2 thoughts on “Dependency Injection in Spring

  1. Hi blogger, i must say you have hi quality content here. Your blog should
    go viral. You need initial traffic boost only. How to get it?
    Search for; Mertiso’s tips go viral

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s