spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误
spring 或 springboot 的 websocket 里面使用 @Autowired 注入 service 或 bean 時,報空指針異常,service 為 null(并不是不能被注入)。
解決方法:將要注入的 service 改成 static,就不會為null了。
參考代碼:
?
本質原因: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。
轉載于:https://www.cnblogs.com/xiaojf/p/11137936.html
總結
以上是生活随笔為你收集整理的spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Actions require uniq
- 下一篇: 第五十二象 乙卯