According to specification of Java EJB (this one is for EJB 3.2. but nothing changed about EJBContext
from previous one, EJB 3.x), you can inject EJBContext
into your components either using annotation @Resource
or manually via lookup (section 11.15):
The container must make a component’s EJBContext interface available either through injection using the Resource annotation or in JNDI under the name java:comp/EJBContext
Standard way of looking up for EJB resource is via EJBContext.lookup
method but there is also JNDI way which is the only possibilities if you don't have already EJBContext
:
Context initCtx = new InitialContext();
EJBContext ejbCtx = (EJBContext) initCtx.lookup("java:comp/EJBContext");
This is exactly what you did, so what is wrong? There are two things, which one I'm not sure about. First, with manually lookup it's sometime needed to assign resource to component with annotation at class level:
@Resource(name = "EJBContext", type = javax.ejb.EJBContext)
public class MyComponent {
...
}
but I'm not sure is it needed for EJBContext
as well, I guess not. The second thing, more important and critical - according to specification once again:
EJBContext objects accessed through the naming environment are only valid within the bean instance that performed the lookup.
this one is section 11.15.1, and the next one, section 11.15.2:
The Container Provider is responsible for providing an appropriate EJBContext object to the refer- encing component. The object returned must be of the appropriate specific type for the bean requesting injection or performing the lookup—that is, the Container Provider must return an instance of the SessionContext interface to referencing session beans and an instance of the MessageDrivenCon- text interface to message-driven beans.
Those both mean that injection and lookup for EJBContext
are only valid in Enterprise Java Beans, so those which are annotated with @MessageDriven
, @Stateful
, @Singleton
or @Stateless
(or described as EJBs in deployment descriptor file, also as EJB 2.x Specification). Maybe your component isn't valid EJB and it's why lookup isn't working? This is only suggestion of course.
There's one more possibilities to get EJBContext
(more correctly SessionContext
). Your component should implements SessionBean
interface which has setSessionContext(SessionContext sessionContext)
method. This method should be invoked by EJB container every time when component is used (injected somewhere, invoked by client or timeout, especially when it's created) and inside this method you should assign sessionContext
parameter to bean's field.