Java Reference
In-Depth Information
WHAT IS DEPENDENCY INJECTION?
The dependency injection pattern is based on the idea of inverting the control. Instead of creating
hard dependencies and creating new objects either with the new keyword or lookups, you inject the
needed resource into the destination object. This approach has many benei ts:
The client does need not to be aware of the different implementations of the injected
resources, making design changes easier.
Unit testing using mock objects is much easier to implement.
Coni guration can be externalized, reducing the impact of changes.
A loosely coupled architecture allows pluggable structures.
The basic idea behind DI is to change the place where objects are created and to use an injector to
inject the specii c implementations to the destination objects at the right moment. This may sound
like an implementation of the factory pattern (see Chapter 6, “Factory Pattern”), but the whole
concept is much more than simple object creation. Inversion of Control (IoC) changes the whole
wiring between objects and lets the injector do the work (most of the time magically). Instead
of calling a factory to provide an implementation to the caller, the injector works proactively to
determine when a destination object needs the target object and performs the injection in the
appropriate way.
IMPLEMENTING DI IN PLAIN CODE
Java did not offer a standard DI implementation out of the Enterprise JavaBeans (EJB) container
until the introduction of Context and Dependency Injection (CDI). Although there are various DI
frameworks, such as Spring and Guice, it is not difi cult to code a basic implementation.
The simplest implementation of DI is a factory that creates the dependency on request via a
getInstance() method. Now you'll implement an example that shows how to do this in plain code.
The simple DI implementation should separate the resolution of dependencies from the behavior of
the class. This means a class should have specii c functionality without dei ning how it obtains a
reference to the classes it depends on. This decouples object creation from where the object is used:
the essence of DI.
You w i ll start by looking at an example in Listings 5‐1, 5‐2, 5‐3 and 5‐4 that is highly coupled, and
refactor it to use your home‐grown DI.
LISTING 5‐1: UserService class that creates a new dependency in the constructor
package com.devchronicale.di;
class UserService {
private UserDataRepository udr;
UserService() {
this.udr = new UserDataRepositoryImpl();
 
Search WWH ::




Custom Search