今天拿到个war包,用Tomcat启动时报错:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpointExporter' defined in class path resource [org/xx/config/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
查了下是由于打包后项目不再依赖内置tomcat,导致了在springboot内置tomcat正常的代码到了外置容器就不能运行
解决方案
方法一,在配置类中把serverEndpointExporter方法注释掉,或者直接删掉
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
// @Bean
// public ServerEndpointExporter serverEndpointExporter() {
// return new ServerEndpointExporter();
// }
}
方法二,为了方便进行项目维护,建议使用@Profile注解,完美解决,省去了开发和发布时候注释代码的操作
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Profile({"dev", "test"})
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Profile注解的参数为字符数组,当项目环境Active profiles为dev或者test时,@bean serverEndpointExporter会正常装配,当Active profiles是其他比如prod的时候,serverEndpointExporter会被忽略不进行装配
本文介绍了解决WebSocket在外部Tomcat服务器上部署时遇到的问题。通过调整配置类,使用@Profile注解来区分不同环境,确保了WebSocket组件在不同场景下的正常运行。

1157

被折叠的 条评论
为什么被折叠?



