Java Reference
In-Depth Information
well as arbitrary values such as strings and integers. There are also other useful
features, such as its support for
AOP
. In comparison,
EJB 3
dependency injection is
a convenient way for
EJB
s to access
JNDI
objects but lacks many of those features
provided by Spring dependency injection. Ideally, we should be able to use the
two dependency mechanisms together and leverage each of their strengths.
The good news is that there is a way to integrate Spring and
EJB 3
dependency
injection. We can use Spring's bean factory mechanism to create and wire
together
POJO
s and use
EJB 3
dependency injection to inject the
POJO
s into
EJB
s.
Not only does this let
EJB 3
applications take advantage of Spring's dependency
injection, but it can also make it easier to incorporate existing Spring code.
We need to do three things to integrate Spring and
EJB
dependency injection:
Expose Spring beans via
JNDI
when the application is initialized.
1
Annotate the session bean class to bind a
JNDI
name to the
EntityManager
and annotate its fields to inject the
POJO
s using
JNDI
.
2
Configure a Spring
JndiObjectFactoryBean
to look up the
EntityManager
via
JNDI
so that it can be injected into the repositories.
3
Let's see how to do approach this task using the
PlaceOrderFacade
EJB
as an exam-
ple. You will learn how to use Spring to create
POJO
s such as
PlaceOrderService
and
RestaurantRepository
and to then inject them into the
PlaceOrderFacade
EJB
. Note that this section describes some aspects of
JNDI
that you might be unfa-
miliar with; I had certainly never used these particular
JNDI
API
s until I tried to do
this integration. Please bear with me as I describe all the different pieces.
Exposing Spring beans via JNDI
As you saw in section 10.1,
EJB
dependency injection is based on
JNDI
; therefore,
if you want to inject a Spring bean into an
EJB
it must be accessible via
JNDI
. We
can do this by binding a name in the
JNDI
tree to a
JNDI
Reference
. A
JNDI
Refer-
ence
is an object that tells the
JNDI
implementation how to find an object that
exists outside of
JNDI
. As figure 10.4 shows, in this particular case the
Reference
acts as a bridge between the
EJB
container and the Spring bean factory.
To expose a Spring bean via
JNDI
, we would create a
Reference
that contains
the name and type of a Spring bean and the name of a
JNDI
ObjectFactory
class
that calls Spring to get the bean. When the
EJB
container does a
JNDI
lookup, it
will find the
Reference
and call the
ObjectFactory
to create the object. The
ObjectFactory
will get the Spring bean by calling
BeanFactory.getBean()
.
Search WWH ::
Custom Search