Java Reference
In-Depth Information
throws Exception {
String beanName = (String) ((Reference) reference)
.get(0).getContent();
return TheBeanFactory.getBean(beanName,
Object.class);
}
}
The
getObjectInstance()
method is called by the
JNDI
implementation when the
EJB
container looks up the bean. It gets the bean name from the
Reference
parameter and calls the Spring bean factory.
Binding the references to the Spring beans
One tricky implementation issue is how and when to bind the references to the
Spring beans into the
JNDI
tree. I've rarely had to explicitly call
JNDI
to bind
names to objects because it has always been done automatically by the
EJB
con-
tainer when deploying an
EJB
or by the application server when creating objects
such as a
JDBC
DataSource
. However, to expose Spring beans via
JNDI
you must
write some initialization code that binds the references.
I originally thought that this could be done by a startup servlet, which is an
easy-to-use and portable way to execute initialization code. However, it turns out
that some application servers such as
JB
oss require the
JNDI
names referenced by
an
EJB
to be bound before the
EJB
is deployed. This is because when the
EJB
con-
tainer deploys an
EJB
it looks up the
JNDI
names referenced by the dependency
injection annotations. The deployment will fail if the name is not found. Because
servlets are usually loaded after the
EJB
s, you cannot use one to bind the
JNDI
ref-
erences. Instead, you must use an application server-specific mechanism.
For example,
JB
oss Application Server 4.0 has a feature called a service
POJO
that can be used to execute initialization code. We won't go into the details of how
a service
POJO
works except to say that it can have a
create()
method that is
called by the application server when it is deployed and a
destroy()
method that
is called when the service
POJO
is undeployed. You can write a service
POJO
that
has a
create()
method that binds the references to the Spring beans and a
destroy()
method that unbinds the references. Here is an example of a service
POJO
class that does just that:
@Service
@Local(SpringBeanReferenceInitializerLocal.class)
public class SpringBeanReferenceInitializer implements
SpringBeanReferenceInitializerLocal,
SpringBeanReferenceInitializerManagement {
Search WWH ::
Custom Search