开发者

Injected EJB sometimes Null

开发者 https://www.devze.com 2022-12-20 06:21 出处:网络
I\'m using a stateless EJB via the @EJB annotation... most of the time everything works as it should but 开发者_开发问答it seems that from time to time what is supposed to be injected resolves to a NU

I'm using a stateless EJB via the @EJB annotation... most of the time everything works as it should but 开发者_开发问答it seems that from time to time what is supposed to be injected resolves to a NULL causing a null pointer exception.

What could cause this intermittent problem?


JBoss 4.x won't automatically inject EJB's into Servlets/JSPs/POJOs. But it won't complain about the annotations either, it simply won't work at runtime, and the objects will remain Null. You have to use JNDI lookup.

From the JBoss docs:

Lookup of EJBs @EJB annotations are usable in servlets and JSPs, but unfortunately, we have not yet updated tomcat to support it. Also, Tomcat works with the old XML format so you cannot use XML either. So for now, you must lookup the EJB via its global JNDI name. This is not compliant, but if you abstract out enough you'll be fine.

Example:

public void init() throws ServletException
   {
      super.init();
      try
      {
         InitialContext ctx = new InitialContext();

         // J2EE 1.5 has not yet defined exact XML <ejb-ref> syntax for EJB3
         CalculatorLocal calculator = (CalculatorLocal)ctx.lookup("tutorial/CalculatorBean/local");
         setCalculator(calculator);
      }
      catch (NamingException e)
      {
         throw new RuntimeException(e);
      }
}

Be sure to use the name of your EAR as the first segment in the name you are looking up (tutorial in the example above).

References:

  • How do I look up an ejb in jBoss 4.2?
  • JBoss docs
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号