我在 EJB Stateless 上使用 JBoss AS 7 和 Schedule 方法。我的问题是即使 EJB 也是无状态的,它保持状态,这给我带来了麻烦。这是示例:
计时器:
@Stateless
public class TestTimer {
@Inject HelloWorldService helloWorld;
@SuppressWarnings("unused")
@Schedule(second="*/10", minute="*", hour="*", info="MyTimer")
private void execute() {
System.out.println(helloWorld.sayHello());
System.out.println(this.toString() + " "+ helloWorld.toString());
}
}
注入(inject)的 HelloWorldService:
public class HelloWorldService {
public String sayHello() {
return "Hello World!";
}
}
我原以为 System.out.println(this.toString() + ""+ helloWorld.toString());
这行会在每次计时器运行时打印不同的时间,因为每次都会是一个新的 TestTimer
实例,但我错了:
16:43:50,003 INFO [stdout] (EJB default - 3) foo.service.TestTimer@4a56936f foo.service.HelloWorldService@79e98289
16:44:40,022 INFO [stdout] (EJB default - 1) foo.service.TestTimer@4a56936f foo.service.HelloWorldService@79e98289
我是不是做错了什么,这是预期的行为,还是什么?
最佳答案
重要的是每个计时器都有一个查找,你可能会得到不同的bean实例
,
但是“可能”意味着您仍然可以获得相同的实例,因为它是从 beans 池中获得的
容器为您管理。
使用相同的计时器对象没有错,
只要它提供适当的功能。
这意味着作为开发人员,您不能对 bean 的状态做出任何假设,并且它是否会在重新查找 bean 时恢复。
关于java - Stateless EJB 使用 EJB Schedule 保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13127790/