踩坑一: 原因: 是因為Spring對象的創建都是以單例模式創建的,在啟動時只創建一次WebSocket。而WebSocketServer在每個連接請求到來時,都會new一個對象。所以當你啟動項目時,你想要註入的對象已經註入進去,但是當用戶連接是,新創建的websocket對象沒有你要註入的對象,所 ...
踩坑一:
原因:
是因為Spring對象的創建都是以單例模式創建的,在啟動時只創建一次WebSocket。而WebSocketServer在每個連接請求到來時,都會new一個對象。所以當你啟動項目時,你想要註入的對象已經註入進去,但是當用戶連接是,新創建的websocket對象沒有你要註入的對象,所以會報NullPointerException
解決:
通過static關鍵字讓webSocketService屬於WebSocketServer類
private static WebSocketService webSocketService; //通過static關鍵字讓webSocketService屬於WebSocketServer類
@Autowired//註入到WebSocketServer類的webSocketService屬性里
public void setKefuService(WebSocketService webSocketService){
WebSocketServer.webSocketService= webSocketService;
}
踩坑二:
使用@ServerEndpoint
聲明的websocket伺服器中自動註入
- 錯誤方法,這樣無法從容器中獲取
@ServerEndpoint(value = "/chat/{username}")
@Service
public class WebSocketServer {
@Resource // @Autowired
private RabbitTemplate rabbitTemplate; //null
}
- 解決:使用上下文獲取
@ServerEndpoint(value = "/chat/{username}")
@Service
public class WebSocketServer {
/*
* 提供一個spring context上下文(解決方案)
*/
private static ApplicationContext context;
public static void setApplicationContext(ApplicationContext applicationContext) {
WebSocketServer.context = applicationContext;
}
}
- 在啟動類中傳入上下文
@SpringBootApplication
public class TalkApplication {
public static void main(String[] args) {
//解決springboot和websocket之間使用@autowired註入為空問題
ConfigurableApplicationContext applicationContext =
SpringApplication.run(TalkApplication.class, args);
//這裡將Spring Application註入到websocket類中定義的Application中。
WebSocketServer.setApplicationContext(applicationContext);
}
}
- 在使用的地方通過上下文去獲取服務
context.getBean()
;
public void sendSimpleQueue(String message) {
String queueName = "talk";
// 在使用的地方通過上下文去獲取服務context.getBean();
RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
rabbitTemplate.convertAndSend(queueName, message);
}