Java Reference
In-Depth Information
5.2. Using EJB DI and JNDI
With Java EE 5, the @EJB annotation was added to the specification to make it easier for
container-managed components to get reference to EJBs. Following the inversion of con-
trol best practice, the container uses the DI pattern to wire up beans. Although JNDI is still
used in the background, those details are hidden from the developer by the @EJB annota-
tion. Prior to EE5, JNDI was used exclusively. The key difference is it was the developer's
responsibility to wire up beans manually using a JNDI implementation of the service locat-
or pattern instead of having the container do it through dependency injection. In this section
we'll first review the basics of JNDI to gain an understanding of what's happening behind
the scenes. Then we'll look at the @EJB annotation in more detail, demonstrating how and
when to use the annotation and how it may also be used in conjunction with JNDI.
Inversion of control (IoC)
Inversion of control is a general programming best practice in the object-oriented world. It
describes that dependencies between objects should be loosely coupled through the use of
interfaces and concrete implementations determined at runtime. The service locator (SL)
pattern and dependency injection pattern follow this best practice.
Dependency injection pattern
DI follows a “push” model. An object's dependencies are configured in some way (XML,
annotations, and so on), and it's the responsibility of a container to create concrete imple-
mentations of these dependencies at runtime and then push the dependencies into the ob-
jects. This is the core technology of CDI (discussed later in the chapter).
Service locator pattern
SL follows a “pull” model. Objects are registered inside a central location service. It's
then the responsibility of the objects to use this central location service to look up or pull
whatever dependencies the object needs into itself. JNDI provides this central location ser-
vice, and objects use JNDI lookups to pull in their dependencies.
Search WWH ::




Custom Search