spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误

Posted xiaojf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误相关的知识,希望对你有一定的参考价值。

spring 或 springboot 的 websocket 里面使用 @Autowired 注入 service 或 bean 时,报空指针异常,service 为 null(并不是不能被注入)。

解决方法:将要注入的 service 改成 static,就不会为null了。
参考代码:

@Controller
@ServerEndpoint(value="/chatSocket")
public class ChatSocket 
// 这里使用静态,让 service 属于类
private static ChatService chatService;

// 注入的时候,给类的 service 注入
@Autowired
public void setChatService(ChatService chatService) 
ChatSocket.chatService = chatService;

 


本质原因:spring管理的都是单例(singleton),和 websocket (多对象)相冲突。
详细解释:项目启动时初始化,会初始化 websocket (非用户连接的),spring 同时会为其注入 service,该对象的 service 不是 null,被成功注入。但是,由于 spring 默认管理的是单例,所以只会注入一次 service。当新用户进入聊天时,系统又会创建一个新的 websocket 对象,这时矛盾出现了:spring 管理的都是单例,不会给第二个 websocket 对象注入 service,所以导致只要是用户连接创建的 websocket 对象,都不能再注入了。

像 controller 里面有 service, service 里面有 dao。因为 controller,service ,dao 都有是单例,所以注入时不会报 null。但是 websocket 不是单例,所以使用spring注入一次后,后面的对象就不会再注入了,会报null。

以上是关于spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误的主要内容,如果未能解决你的问题,请参考以下文章

后端向前端推送消息

springboot2 -广播式WebSocket

websocke

Springboot-WebSocket初探-获取HttpSession问题

websocke前世今生

websocke 在线测试地址