0%

SpringBoot Websocket 注入bean失败

踩坑记录

第一种方式:将messageService 注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

//这里使用静态,让 service 属于类
public static MessageServiceImpl messageService;

/**
* 给类的service 注入
* spring管理的都是单例(singleton)和 websocket (多对象)相冲突
*
* @param messageService
*/
@Autowired
public void setMessageService(MessageServiceImpl messageService) {
WebSocketServer.messageService = messageService;
}
}

第二种方式
或者将

1
2
3
4
@Autowired
public void setMessageService(MessageServiceImpl messageService) {
WebSocketServer.messageService = messageService;
}

写在websocketConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class WebSocketConfig {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

/**
*手动注入一个全局变量
* @param messageService
*/
@Autowired
public void setMessageService(MessageServiceImpl messageService) {
WebSocketServer.messageService = messageService;
}
}

欢迎关注我的其它发布渠道