现象
websocket里无法注入其它@Compenent 、@Service、@Resource、@Autowired、@Value等单例组件
原因
spring管理的都是单例(singleton),和 websocket (多对象)相冲突。
websocket 不是单例,是动态生成的,因此无法注入单例组件。
像 controller 里面有 service, service 里面有 dao。因为 controller,service ,dao 都有是单例,所以注入时不会报 null。但是 websocket 不是单例,所以使用spring注入一次后,后面的对象就不会再注入了,会报null。
解决
- 使用如下方式
- 将获取方式写在外部类即可避免
@ServerEndpoint("/websocket")@ComponentpublicclassWebSocketServer{// 要注入的组件privatestaticSendConfigsendConfig;@AutowiredpublicvoidsetSendConfig(SendConfigsendConfig){WebSocketServer.sendConfig=sendConfig;}}本文与Autowired/Resource注入失败如何解决?相关