我在使用带有 @ServerEndPoint 注释类的 spring 时遇到问题
我正在使用 Springboot 1.2.3,我试图弄清楚如何拥有一个端点实例
@SpringBootApplication
@EnableJpaRepositories
@EnableWebSocket
public class ApplicationServer {
public static void main(String[] args) {
SpringApplication.run(ApplicationServer.class, args);
}
}
弹簧配置:
@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {
@Bean
public ServerEndPoint serverEndpoint() {
return new ServerEndPoint();
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocket 端点:
@ServerEndpoint(value = "/", decoders = MessageDecoder.class,
encoders = MessageEncoder.class, configurator = SpringConfigurator.class)
public class ServerEndPoint {
private static final Logger LOG = LoggerFactory.getLogger(ServerEndPoint.class);
public static final Set<CommunicationObserver> OBSERVERS = Sets.newConcurrentHashSet();
@OnMessage
public void onMessage(Session session, Message msg) {
LOG.debug("Received msg {} from {}", msg, session.getId());
for (CommunicationObserver o : OBSERVERS) {
o.packetReceived(session, msg);
}
}
这是基于Spring WebSocket JSR-356 教程,但我收到以下错误:
java.lang.IllegalStateException: Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?
at org.springframework.web.socket.server.standard.SpringConfigurator.getEndpointInstance(SpringConfigurator.java:68)
at org.apache.tomcat.websocket.pojo.PojoEndpointServer.onOpen(PojoEndpointServer.java:50)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:138)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
我已经在嵌入式模式和外部 tomcat 8 和 jetty 9 下进行了测试(在外部模式下,我删除了 de Spring 配置文件),但出现了同样的错误。
public class SpringEndpointConfigurator extends ServerEndpointConfig.Configurator {
private static WebApplicationContext wac;
public SpringEndpointConfigurator() {
}
public SpringEndpointConfigurator(WebApplicationContext wac) {
SpringEndpointConfigurator.wac = wac;
}
@Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
T endPoint = wac.getAutowireCapableBeanFactory().getBean(endpointClass);
return (endPoint != null) ? endPoint : wac.getAutowireCapableBeanFactory().createBean(endpointClass);
}
它被创建为带有参数化构造函数的@Bean。
我一定错过了使用 SpringConfigurator 类完成它的东西,但我不知道是什么。