Tuesday, March 16, 2010

Dependency Injection

Listing 1:
public class A {
   B b;
   
   public A(B b){
      this.b = b;
   }
}

A a = new A(new B());

In the above listing we have created a Class A which depends on another Class B.

In object oriented programming it is better to use interface or abstract types so that there is a flexibility in terms of implementation. Given this lets change the code to the one shown in listing 2.

Listing 2:
public interface IB{
}

public class B implements IB { }

public class A{
       private IB b;
       public A(IB b){
          this.b = b;
       }
}

As evident from the Listing 2 we now have an interface IB and B is one of the classes that implements it. We now can have B', B1 etc implementation of IB.

Given all this we can now create an object of B and pass it to the constructor of class A.

A a = new A(new B())

Now if I tell you that the Class B is dependent on Class C which is dependent of Class D etc there will be similar type of code that we will write to pass them around in either constructors or setter methods.

While this type of code structure helps in choosing the appropriate implementation (at coding time) it is not ideal for situations when the implementations are supposed to be chosen at runtime i.e. not by the developer rather by the deployer of the application.

This is where spring framework comes and help in specifying the object graph/dependencies in an XML file. The objects are  called beans and the process of specifying the dependencies is called wiring of beans.


<beans>

<bean id="my_b" class="B">
</bean>

<bean id="my_a" class="A">
<constructor-arg ref="my_b"/> 
</bean>

</beans>


In the above XML file (mybeans.xml) we specified a bean with id "my_a" and tell that its constructor argument should be the bean "my_b "whose class is B.

This XML language is sophisticated enough to specify constructor arguments, set properties (setter/getter java methods) and many more things.

Your application code then becomes:

ClassPathApplicationContext applicationContext = new ClassPathApplicationContext("mybeans.xml")

A a = (A)applicationContext.getBean("my_a");

As evident from this example we did not create any objects in our code rather they were created by the spring framework and are accessible to us in the code using an API getBean by passing the id of the object we desire.

Read more about these topics here:

No comments:

Post a Comment