springboot 中 websocket 注入 service

在websocket 中直接注入 @Autowired 会发现空值异常

解决办法:

1.在websocket类中 将要注入的 service 设置静态变量
@Component
@ServerEndpoint(value = "/plcWeb", encoders = EncoderClassVo.class)
@Slf4j
public class PLCWebSocketController {

    public static PLCService plcService;
    private Session session;
    private static CopyOnWriteArraySet<PLCWebSocketController> webSocketSet = new CopyOnWriteArraySet<>();
	.......
}
2.在websocketConfig 中配置注入
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    @Autowired
    public void setPLCService(PLCService plcService){
        PLCWebSocketController.plcService = plcService;
    }
}
posted @ 2021-09-23 16:31  无小空空  阅读(434)  评论(1编辑  收藏  举报