问题描述
在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) {
We