2. Dependency Injection To The Rescue

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.

Table 1. Dependency Injection Types

DI TypeDescription
Constructor InjectionThe constructor arguments are injected during instance instantiation.
Setter InjectionThis 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 InjectionThis 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. In the next section we will discuss Spring's IoC container and how it makes use of dependency injection patterns to make your code, well, RFI-free, and just better.



[4] Martin Fowler, Inversion of Control Containers and The Dependency Injection Pattern