我记录了一些消息来查看@ServerEndpoint
的生命周期。 PostConstruct
、onOpen
、onClose
会依次触发,但 @PreDestroy
不会被触发。我错过了什么吗?
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/")
public class ServerWebSocket {
@PostConstruct
public void initialize() {
System.out.println("PostConstruct");
}
@OnOpen
public void open(Session session) {
System.out.println("OnOpen");
}
@OnClose
public void close(Session session) {
System.out.println("OnClose");
}
@PreDestroy
public void destroy() {
System.out.println("PreDestroy");
}
}
我在 WEB-INF 中使用 GlassFish4 和 bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
最佳答案
@OnOpen
和 @OnClose
回调由每个 WebSocket session 的生命周期触发。
没有指定任何可以与 WebSocket 端点一起使用的 CDI 范围。这没关系,因为它有自己的 session 。
那么,为什么会触发@PostConstruct
? WebSocket 规范指出:
Websocket endpoints running in the Java EE platform must have full dependency injection support as described in the CDI specification.
和@PostConstruct
API 文档要点:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. ... This annotation MUST be supported on all classes that support dependency injection.
为什么@PreDestroy
不起作用?我认为,Websocket 端点的行为类似于单例,并且 @PreDestroy 将在删除实例期间被触发,这将在应用程序停止之前发生。您可以通过从 GlassFish 管理控制台停止应用程序来在您的环境中检查它。
关于java - 为什么 @PreDestory 不能在 websocket @ServerEndpoint 上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309085/