【问题标题】:How to use @PostConstruct to create timers in a stateless bean EJB3?如何使用@PostConstruct 在无状态 bean EJB3 中创建计时器?
【发布时间】:2010-08-15 19:35:56
【问题描述】:

我想在池中创建无状态 bean 时创建一个计时器 EJB3。 但如果我使用 @PostConstruct 我会得到异常:

java.lang.IllegalStateException: [EJB:010193]Illegal call to EJBContext method. The bean is in "null" state. It cannot perform 'getting the Timer Service' action(s). Refer to the EJB specification for more details.

如果容器调用@PostConstruct,则 bean 不会为空。那么,为什么我会得到这个异常?


@Stateless
public class TestBean implements TestLocal {

    @Resource
    TimerService timerService;

    @PostConstruct
    public void startTimer() {
        if (timerService.getTimers().size() == 0) {
            timerService.createTimer(1 * 1000, 1 * 1000, null);
        }
    }

    @Override
    public void test() {        
    }

}

界面

@Local
public interface TesteLocal {

    void test();

}

伺服器

public class TestServlet extends HttpServlet {
    @EJB
    private TestLocal test;

    protected void doGet(....) throws .... {
        test.test();
    }
}

详情

我正在使用 weblogic server 11g。

【问题讨论】:

    标签: java jakarta-ee ejb-3.0 weblogic weblogic11g


    【解决方案1】:

    您不能使用@PostConstruct 在无状态 bean EJB 3 中创建计时器。有关说明,请参阅此博客 How to use EJB 3 timer in a weblogic 10 cluster environment。甚至博客都在谈论 weblogic,但解释也应该适用于其他应用服务器。

    【讨论】:

    • 是的,同样的问题出现在 JBoss 中
    • 虽然这解释了为什么这是不可能的,但它并没有给出问题的实际答案。
    【解决方案2】:

    容器将不允许在使用无状态会话 Bean 的 @PostConstruct 注释的方法中使用 timerService。如果您想在使用 @PostConstruct 注释的方法中使用 timerService,请使用单例会话 bean(@Singleton)。

    【讨论】:

      【解决方案3】:

      我不是 100% 确定,但我认为 bean 类必须实现 javax.ejb.TimedObject 或具有使用 @Timeout 注释的方法才能使用 EJB 计时器。示例:

      @Stateless
      public class TestBean implements TestLocal {
      
          @Resource
          TimerService timerService;
      
          @PostConstruct
          public void startTimer() {
              if (timerService.getTimers().size() == 0) {
                  timerService.createTimer(1 * 1000, 1 * 1000, null);
              }
          }
      
          @Timeout
          @TransactionAttribute(value=REQUIRES_NEW)
          public void timeoutCallback(Timer timer) {
              ...
          }
      
      }
      

      WebLogic 是否仍然抱怨上面的代码?

      PS:无论如何,您当前收到的错误报告非常差,您可能应该打开一个案例。

      【讨论】:

      • 我按照您的示例进行了 2 处更改:a)TestLocal 有一个由 TestBean 实现的方法(没有这个,weblogic 无法部署)b)创建一个调用 EJB 的 servlet。错误仍然发生。
      • @Topera 我真的不确定(我什至不确定我的建议对于 EJB 3.0 是强制性的)。我可能错了,但这看起来像一个错误。我建议联系支持
      • 确实,正如 Mike 所说,这段代码不会运行。无法从 @Postconstruct 方法访问或启动计时器。
      猜你喜欢
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多