項目需要長連接業務,我使用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的配合下,成功訪問數據庫,讀取到了需要的數據: