Inject a EJB into a JSF converter with JEE6

Michael Bavin picture Michael Bavin · Jan 7, 2010 · Viewed 13.1k times · Source

I have a stateless EJB that acceses my database. I need this bean in a JSF 2 converter to retreive an entity object from the String value parameter. I'm using JEE6 with Glassfish V3.

@EJB annotation does not work and gets a NPE, because it's in the faces context and it has not access to the EJB context.

My question is: Is it still possible to Inject this bean with a @Resource or other annotation, or a JNDI lookup, or do I need a workaround?


Solution

Do a JNDI lookup like this:

  try {
   ic = new InitialContext();
   myejb= (MyEJB) ic
     .lookup("java:global/xxxx/MyEJB");   
  } catch (NamingException e) {
   e.printStackTrace();
  }

Answer

ewernli picture ewernli · Jan 7, 2010

I never used JSF 2.0 (only 1.0), but chapter 5.4 of the spec says:

[...] allow the container to inject references to container managed resources into a managed bean instance before it is made accessible to the JSF application. Only beans declared to be in request, session, or application scope are eligble for resource injection.

But so far I understand, a JNDI lookup should do the trick.