Java Reference
In-Depth Information
This pattern also consolidates object creation in only a handful of factory classes,
making it easy to maintain. With a factory helper, it is also possible to make object cre-
ation configurable. You can define the concrete implementation that you supply in some
properties or XML configuration files, making it swappable on the fly.
Locate in Registry Service
This third method should be familiar with EJB developers. They often need to look up EJB
object references on the JNDI registry service. In this case, the EJB objects are already cre-
ated and registered in JNDI with a specific key. The objects may be located in a remote
JVM, but JNDI makes lookup using this key quite similar to Listing 2-2.
All these strategies are commonly called pull dependency injection. This is because
the dependent object is pulled in by the object that ultimately uses it. I prefer to classify
the pull methods as dependency resolution, rather than dependency injection. This is
because the true dependency injection happens with IOC and is called push DI. In this
approach, an external container or application framework creates and passes the
dependent object to the object that requires it. The dependent objects are mostly sup-
plied using constructor or setter methods. However, for this the application framework
must know which dependent object to provide and which object to notify with the
dependent object.
It is interesting to note that EJB containers support not only pull DI (one session
bean looking up another session bean, for instance, in the JNDI) but also push DI. This is
evident from the setSessionContext(javax.ejb.SessionContext ctx) or setEntityContext
(javax.ejb.EntityContext ctx) method where the context object is created, initialized,
and passed to the EJB objects by the container. This is called setter injection . You can
explore different varieties of push DI with examples in a later section when I touch upon
the DI features of Spring IOC container.
Benefits of DI
The following are the benefits of DI:
• Dependency injection promotes loose coupling. With a factory helper, for instance,
you can remove hard-coded dependencies through P2I. It is possible to configure
them outside the application and provide hot-swappable and hot-pluggable
implementations.
• It facilitates test-driven development (TDD). Objects can be easily tested because
they do not require any particular container to run. They can be tested as long as
the dependencies are injected by some mechanism.
 
Search WWH ::




Custom Search