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.

About these ads

One thought on “Dependency Injection in Spring

  1. Pingback: Introduction to Spring Part II - Bean, BeanFactory, ApplicationContext, IOC, Dependecy Injection « Java stories.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s