SpringBoot中WebSocket不能實現注入的問題
阿新 • • 發佈:2019-02-12
專案需要長連線業務,我使用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的配合下,成功訪問資料庫,讀取到了需要的資料: