問題描述
在SpringBoot中使用WebSocket時使用@Autowire自動注入Bean爲null,導致程序無法正常運行
查了些資料,順利解決問題,關於問題發生的原因,以下是個人見解,不對的地方請指正!
Spring IOC容器管理Bean的默認是單例的,但是每一個客戶端對應一個WebSocket,很顯然WebSocket是多例的,當有客戶端連接時纔會實例化一個WebSocket,自動裝配發生在SpringBoot啓動時,無法爲WebSocket注入Bean
解決辦法
既然SpringBoot在運行時無法爲WebSocket注入Bean,那麼可以在SpringBoot啓動時手動注入Bean,並且該Bean應該是static的
- 首先在SpringBoot初始化時獲取ApplicationContext
- 通過applicationContext.getBean(Bean.class)來獲取Spring IOC容器中的Bean
- 將獲取到的Bean通過靜態方法注入到WebSocktController
以下是代碼:
WebSocketController.java
@Controller
@ServerEndpoint("/websocket")
public class WebSocketController {
private static MyService myService;
// 靜態方法、在SpringBoot啓動時被調用
public static void setMyService(MyService myService) {
WebSocketController.myService = myService;
}
......
}
MySpringBootApplication.java
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(MySpringBootApplication.class);
ApplicationContext applicationContext = springApplication.run(args);
// 獲取Spring IOC容器中的Service並注入
MyService myService = applicationContext.getBean(MyService.class);
WebSocketController.setMyService(myService);
}
}