我是 Spring 新手(并且在 stackoverflow 上提问)。
我想通过 Spring Boot 启动嵌入式(Tomcat)服务器并向其注册 JSR-356 WebSocket 端点。
这是主要方法:
@ComponentScan
@EnableAutoConfiguration
public class Server {
public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}
这是配置的外观:
@Configuration
public class EndpointConfig {
@Bean
public EchoEndpoint echoEndpoint() {
return new EchoEndpoint();
}
@Bean
public ServerEndpointExporter endpointExporter() {
return new ServerEndpointExporter();
}
}
EchoEndpoint
实现很简单:
@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)
public class EchoEndpoint {
@OnMessage
public void handleMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText("echo: " + message);
}
}
对于第二部分,我关注了这篇博文:https ://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support 。
但是,当我运行应用程序时,我得到:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpointExporter' defined in class path resource [hello/EndpointConfig.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Failed to get javax.websocket.server.ServerContainer via ServletContext attribute
该异常进一步是由NullPointerException
in引起的ServerEndpointExporter
,因为此时返回的getServletContext
方法applicationContext
仍然存在null
。
对Spring有更好理解的人可以帮助我吗?谢谢!