Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Dependency Injection (DI) or Inversion of Control (IOC) in Spring

Dependency Injection (DI) or Inversion of Control (IOC) in Spring


There are many ways to instantiate an Object, one of the most popular approach is using "new"operator.

      Object ob = new Object();

If we are instantiating one object in other then there is a dependency between those two objects or else we should call they are tightly coupling with each other.

interface Tester{
  //
}
Class Test1 implements Tester{                            Class Test2 implements Tester{

 //  Operations to do                                                //Operations to do

}                                                                                }


Class Verify{
   
  Tester test1;
   public void verification(){
       test1=new Test1();   // Test is tightly coupled with Verify, at run time we cant change this value.
   }
}

In the above scenario Test1 is tightly coupled with Verify. In future if we doesn't want to use Test1 instead we should use Test2 in that case we have to do modifications in java code which is not recommendable. If we use Dependency Injection between objects then we can inject objects run time in xml file instead of inside class.

Class Verify{

Tester test1;
public void setTest1(Tester test1){
   this.test1=test1;
}
   public void verification(){
   //use test1 object directly
}
}

/*   In side Spring Container */
<bean id="test1"  class="pkg.Test1"/>
<bean id="test2"  class="pkg.Test2"/>
<bean id="verify"  class="pkg.Verify">
  <property name="test1" ref="test1"/>  //if we doesn't want to use test1 then change here test2
</bean>

Advantages:

1)  Loosely coupled code so easy to maintain.
2)  Easy to Test






This post first appeared on Java Spring Hibernate, please read the originial post: here

Share the post

Dependency Injection (DI) or Inversion of Control (IOC) in Spring

×

Subscribe to Java Spring Hibernate

Get updates delivered right to your inbox!

Thank you for your subscription

×