1、使用websocket打包时失败
在打包时出错: PrivatemsgApplicationTests.contextLoads >> IllegalState Failed to load Applicat…
跳过test 注释掉 runwith(SpringRunner.class)即可成功打包
2、使用websocket后运行测试类抛异常
在配置了ServerEndpointExporter的bean后,运行测试类出现了Error creating bean with name 'serverEndpointExporter
原因是websocket需要依赖tomcat等容器启动。所以在测试的时候需要真正的启动一个tomcat作为容器。
解决方法:
1、将@RunWith(SpringRunner.class) 去掉即可,但是这种方式会有局限,比如下方你要@Authwired一个类的时候会报错
2、在SpringBootTest后加上(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 即可
RANDOM_PORT加载EmbeddedWebApplicationContext,并提供一个真实 的servlet环境。
使用该模式内嵌容器将启动,并监听在一个随机端口。
3、使用websocket内自动注入失败
1、@ServerEndpoint(value="/websocket/{playerId}",configurator = SpringConfigurator.class)
加上configurator 使spring注入可用
2、设置成静态属性用set方法注入
本质原因:spring管理的都是单例(singleton),和 websocket (多对象)相冲突。
详细解释:项目启动时初始化,会初始化 websocket (非用户连接的),spring 同时会为其注入 service,该对象的 service 不是 null,被成功注入。
但是,由于 spring 默认管理的是单例,所以只会注入一次 service。
当新用户进入聊天时,系统又会创建一个新的 websocket 对象,这时矛盾出现了:spring 管理的都是单例,不会给第二个 websocket 对象注入 service,
所以导致只要是用户连接创建的 websocket 对象,都不能再注入了。
像 controller 里面有 service, service 里面有 dao。因为 controller,service ,dao 都有是单例,所以注入时不会报 null。
但是 websocket 不是单例,所以使用spring注入一次后,后面的对象就不会再注入了,会报null。
3、
在启动类中加上
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
//解决WebSocket不能注入的问题
MessageController.setApplicationContext(configurableApplicationContext);
//此处是解决无法注入的关键
private static ApplicationContext applicationContext;
//你要注入的service或者dao
private CDSocketMessageService cdSocketMessageService;
public static void setApplicationContext(ApplicationContext applicationContext) {
MessageController.applicationContext = applicationContext;
}
最后通过applicationContext取出想要注入的bean