Wednesday, 5 November 2014

Dependency Injection


This concept says 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 (the IOC container) is then responsible for hooking it all up.


Types of IoC are:
  • Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Example -


Setter-based dependency injection - 
 <beans>  
      <bean id="test" class="com.test">  
        <property ref="myObj"/>  
      </bean>  
      <bean id="myObj" class="com.test.MyObject">         
      </bean>       
 </beans>  



Constructor-based dependency injection - 
 <beans>  
      <bean id="test" class="com.test.Test">  
        <constructor-arg ref="myObj"/>  
      </bean>  
      <bean id="myObj" class="com.test.MyObject">         
      </bean>       
 </beans>  

No comments: