Java Reference
In-Depth Information
In an
EJB 3
application, there are three ways to use dependency injection. One
option is to use
EJB 3
dependency injection to wire the components together. The
second is to integrate the Spring and
EJB
dependency injection mechanisms. The
third is to only use Spring dependency injection. Let's look at how to use each of
these approaches.
10.4.1
Using EJB dependency injection
One of the exciting new features of
EJB 3
is dependency injection, which is an
easy-to-use mechanism that enables a session or message-driven bean to acquire
references to other
EJB
s and resources without explicit coding. It uses annotations
on fields and setters that specify the objects to inject. When the container instanti-
ates a session or message-driven bean, it will initialize the fields and call the setters
with the specified objects. However, as you learned in section 10.1.2, a significant
limitation of
EJB 3
is that the dependencies must be looked up via
JNDI
and can
only be injected into
session and message-driven EJB
s.
Application components must be EJBs
To use
EJB 3
dependency injection to wire together a façade and its components,
the components must be available through
JNDI
lookup. Moreover, if those com-
ponents use dependency injection, then they must also be
EJB
s. The simplest
approach is to implement the façade's components as stateless session beans. For
example, to configure the
PlaceOrderFacade
using
EJB
dependency injection, all
of the classes shown earlier in figure 10.3 must be implemented as session beans.
Fortunately, it is easy to turn
POJO
s such as domain services and repositories
into session beans. As you saw earlier, you just need to annotate the interface with
@Local
and the implementation class with
@Stateless
. However, for this to be
practical the overhead of one session bean calling another via a local interface
must be low. In addition, the development environment and the
EJB
container
must be able to handle the increased number of
EJB
s without significantly increas-
ing the deployment time.
Let's now look at the annotations we must use to configure the
PlaceOrder-
Facade
and its components.
Annotating a POJO façade
To initialize a
POJO
façade using dependency injection, we must annotate each
field that references an
EJB
with an
@EJB
annotation in order to tell the
EJB
con-
tainer to inject an
EJB
. Here is an excerpt from the
PlaceOrderFacade
that shows
how to do this:
Search WWH ::
Custom Search