Saturday 28 June 2014

What is Dependency Injection in Spring ? Explain types and advantages with examples

             Spring uses inversion of control to satisfy dependencies between objects. Traditional approach before Spring framework was to hard code the dependencies and this creates tightly coupled code and there was no easy way to change that. People used to minimize this tight coupling, by resorting to ” programming to an interface and not to an implementation”, but even with that approach, the actual creation of the dependent object was the responsibility of the calling piece of code. Of course there were custom frameworks being developed by various individuals to create some form of  inversion of control to achieve dependency injection ( DI). 

            The basic concept of the Inversion of Control pattern  is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked.  
    
        There are two types of DI,

  • Setter Injection
  • Constructor Injection                                                                 

Setter Injection:-

    Spring framework will inject the dependency via a setter method.
XML configuration for setter Dependency Injection is below.

  <bean id="classBean" class="com.adnjava.ClassBean">
     <!-- setter injection using the nested <ref/> element -->
       <property name="studentBean"><ref bean="studentBean"/></property>
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/> 

         The ClassBean java POJO class is as below,

 package com.adnjava;

  public class ClassBean {

       private StudentBean studentBean;

       public void setStudentBean(StudentBean studentBean){
           this.studentBean=studentBean;
       }

       public void getStudentBean(){
             return studentBean;
       }
 }

             

 Constructor Injection:-


          Here Spring uses the  Constructor and the arguments passed to it to determine the dependency. Rest all is same as setter injection.
     
      XML configuration for
Constructor Dependency Injection is below.


  <bean id="classBean" class="com.adnjava.ClassBean">
       <constructor-arg><ref bean="studentBean"/></constructor-arg>
      <!--OR you can use <constructor-arg ref="yetAnotherBean"/>-->
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/>  

         The ClassBean java POJO class is as below,

 package com.adnjava;
  
  public class ClassBean {

         private StudentBean studentBean;

         public ClassBean(StudentBean studentBean){
              this.studentBean=studentBean;
         }

         public void getStudentBean(){
               return studentBean;
         }
  }


              Interface Injection:

             This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.

                    

Advantages Of Dependency Injection:

  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate.
  • Using configuration, you can provide implemented code  without changing the dependent code.
  • Testing can be performed using mock objects.

Related Post:--
Spring MVC workflow with example  
Spring MVC with Hibernate CRUD Example  
Spring Annotations  

2 comments:

  1. Hello There,

    Thank you! Thank you! Thank you! Your blog was a total game changer!

    I am going toimplement the blackbox class "messagePool". Details are as below. I just want to implement it so that the whole application can run.

    // Call messagePool

    Java Code:

    Dac dac =
    GenericDac.getInstance();

    String result =
    dac.getMessagePool().getMessage(languageCode, key);

    public abstract interface Dac extends java.io.Serializable{

    public abstract void init(javax.servlet.ServletContext
    arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3,
    java.lang.String arg4) throws com.jos.adf3.core.exception.DacInitException;

    public abstract com.pool.MessagePool getMessagePool();

    }

    public class GenericDac implements Dac{

    private com.pool.MessagePool messagePool;

    }

    Super likes !!! for this
    amazing post. I thinks
    everyone should bookmark this.

    Regards,
    Morgan

    ReplyDelete
  2. thank you for your interesting infomation. 2k moulding

    ReplyDelete