views:

540

answers:

1

I have created an EAR with a web project, ejb3 project and the ejb client. I'm able to call the bean methods via injection in the servlet. I'm planning to use a ServiceDelegate which is a pojo to handle the bean invocation. So I'll call the delegate from my servlet and the delegate will call the appropriate beans and its methods.

But I'm unable to get the bean references in the delegate class which is in the web project. @EJB annotation returned a null reference. So I tried a JNDI lookup with java:comp/env/EARname/BeanName. But I always end up with naming exceptions.

Name comp/env/EARname not found in context "java:".

Please suggest me the correct way to call ejb3 beans via JNDI on Websphere 7 server.

+1  A: 

Dependency injection in Java EE 5 and 6, works only for managed classes. In the servlet container, this is supported in a few types of classes, and not in all POJOs (unfortunately).

The Servlet Spec 2.5 sheds light on the classes for which the container must inject dependencies if they are present:


Component Type: Servlets

Classes implementing the following interfaces

  • javax.servlet.Servlet

Component Type: Filters

Classes implementing the following interfaces:

  • javax.servlet.Filter

Component Type: Listeners

Classes implementing the following interfaces:

  • javax.servlet.ServletContextListener
  • javax.servlet.ServletContextAttributeListener
  • javax.servlet.ServletRequestListener
  • javax.servlet.ServletRequestAttributeListener
  • javax.servlet.http.HttpSessionListener
  • javax.servlet.http.HttpSessionAttributeListener

Therefore, if you have to resolve the issue with dependency lookups, you could adopt either of the following strategies:

  • Inject the dependency into a managed class, and propagate it to the ServiceDelegate. This is a design smell IMHO.
  • Perform a JNDI lookup using the InitialContext, but you should be aware of the JNDI bindings generated for the EJBs that you have deployed. This appears to be failing since the JNDI name might be incorrect - the Java EE specification has not standardized the JNDI names that are assigned to the deployed EJBs. In other words, given the lack of portable JNDI names, you should attempt to bind the EJB to a known name and perform a lookup of the same.
  • You'll need to verify that the EJB session object is indeed bound to the java:comp/env namespace. This might not be the case. To be clear, if the dependency is not injected by the container, then one must declare the local EJB reference entries in web.xml. The container will not automatically inject the session EJB objects into the servlet's namespace; it will require the EJB to be declared as a resource in a managed class. This appears to be the primary case of failure, although it is listed last.
Vineet Reynolds
Note that *anything* can be turned into a managed bean in Java EE 6 with CDI.
Pascal Thivent