我在单例的 preDestroy 方法中访问无状态 EJB 时遇到问题。我需要在数据库表中记录应用程序服务器的关闭。
这就是单例的样子:
@Startup
@Singleton
public class ServerShutdown {
@EJB
TableFacade tableFacade;
@PreDestroy
private void shutdown() {
TestEntity e = tableFacade.find("test");
//do something
}
}
以下是无状态 bean 的示例代码:
@Stateless
public class TableFacade {
...
public TestEntity find(String test) {
Query query =
getEntityManager().createNamedQuery("TestEntity.namedQuery");
return (TestEntity) query.getSingleResult();
}
}
如果服务器正在关闭,则访问 preDestroy 方法并调用 EJB 方法。但在调用过程中,服务器似乎强制关闭进程并取消EJB方法的调用。
我使用的是 Java EE 6、JDK 1.8、EJB 3.1、eclipselink 2.5.2。
提前致谢
最佳答案
@predestroy
应该只进行 ejb 资源清理,例如连接、变量等...
您的问题与事务上下文有关,事实上从规范来看:
The PreDestroy lifecycle callback interceptor methods for stateless and stateful session beans execute in an unspecified transaction context.
然后:
For example, it would be wrong to perform database operations within a stateful session bean’s PostConstruct or PreDestroy lifecycle callback interceptor methods and to assume that the operations are part of the client’s transaction. The PostConstruct and PreDestroy methods for stateful and stateless session beans are not controlled by a transaction attribute because handling rollbacks in these methods would greatly complicate the session instance’s state diagram.
因此,这并没有明确禁止,但会警告您,事情可能会出错。
关于java - 在 Singleton 的 PreDestroy 方法中访问无状态 EJB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273157/