Monday, October 22, 2012

Dependency Inversion & IOC Container


Dependency Inversion : Precursor to Dependency Injection
The first reference to what would eventually become Dependency Injection appeared in 1994 in a paper by Robert C. Martin called “The Dependency Inversion Principle”.
In “The Dependency Inversion Principle” (or DIP), the author states the three defining factors of “bad code”:

1. It is hard to change because every change affects too many other parts of the system (Rigidity)
2. When you make a change, unexpected parts of the system break (Fragility)
3. It is hard to reuse in another application because it cannot be disentangled from the current application(Immobility) 

According to Martin, interdependency causes these coding problems (we'll call them RFI for Rigidity, Fragility, and Immobility). To fix RFI issues in your OO code, DIP has two basic rules:
1. High level modules should not depend upon low level modules, both should depend upon abstractions.
2. Abstractions should not depend upon details, details should depend upon abstractions.

Dependency Injection takes the level of decoupling that began with the Dependency Inversion Principle one step further. Dependency injection has the concept of an assembler 4 – or what in Java is commonly referred to as a Factory -- that instantiates the objects required by an application and “injects” them into their dependent objects.
In the case of a dependency injection-informed framework such as Spring, components are coded to interfaces, just as in the DIP example above. But now the IoC container manages the instantiation, management, and class casting of the implemented objects so that the application doesn't have to. This removes any true dependencies on low-level
implemented classes.

There are three types of Dependency Injection employed by IoC container providers.
  • Constructor Injection : The constructor arguments are injected during instance instantiation. 
  •  Setter Injection : This is the most favored method of dependency injection in Spring. Dependencies are “set” in the objects through setter methods defined in a Spring configuration file.
  • 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.


Spring uses the concept of a BeanFactory as its assembler, and it is the BeanFactory that manages the JavaBeans you have configured to run within it.

No comments:

Post a Comment