在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;
}
}