如何使用@PostConstruct在无状态bean EJB3中创建计时器?

Top*_*era 4 java weblogic java-ee weblogic11g ejb-3.0

我想在池中创建无状态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不为null.那么,为什么我得到这个例外?


@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() {        
    }

}
Run Code Online (Sandbox Code Playgroud)

接口

@Local
public interface TesteLocal {

    void test();

}
Run Code Online (Sandbox Code Playgroud)

SERVLET

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

    protected void doGet(....) throws .... {
        test.test();
    }
}
Run Code Online (Sandbox Code Playgroud)

细节

我正在使用weblogic服务器11g.

小智 7

您不能使用@PostConstruct在无状态Bean EJB 3中创建计时器.请参阅此博客如何在weblogic 10集群环境中使用EJB 3计时器进行说明.甚至博客也在谈论weblogic,但解释也应该适用于其他应用服务器.

  • 尽管这解释了为什么这是不可能的,但它并没有给出问题的实际答案。 (2认同)

Pas*_*ent -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) {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

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

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