项目需要长连接业务,我使用SpringBoot中的 ,一切都调得好好的,到对接数据库的时候,一个大坑突然出现:ServerEndpoint中竟然不能实现注入,甚至使用的对象中有注入也不行。找了两天资料,写了好几个demo,有人说在@ServerEndpoint加上, configurator = SpringConfigurator.class,测试不通过;有人说使用 ContextLoader.getCurrentWebApplicationContext(),貌似也不行。甚至尝试过把jpa改成idbc也不行。
后来在https://segmentfault.com/q/1010000010103973这篇文章中找到了突破。
1.首先需要在ServerEndpoint中加上这一部分:
private static ApplicationContext applicationContext;
private WsService wsService;
public static void setApplicationContext(ApplicationContext applicationContext) {
MsgCenter.applicationContext = applicationContext;
}
2.在onOpen()方法中加入:
wsService = applicationContext.getBean(WsService.class);
3.把SpringBoot的启动类改造成这个样子
public class Application {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
MsgCenter.setApplicationContext(configurableApplicationContext);//解决WebSocket不能注入的问题
}
}
重新运行,在Android的配合下,成功访问数据库,读取到了需要的数据: