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 是多对象的,每个用户的聊天客户端对应 java 后台的一个 websocket 对象,前后台一对一(多对多)实时连接,所以 websocket 不可能像 servlet 一样做成单例的,让所有聊天用户连接到一个 websocket对象,这样无法保存所有用户的实时连接信息。可能 spring 开发者考虑