在websocket中使用@ServerEndpoint無法注入@Autowired、@Value
問題分析
Spring管理采用單例模式(singleton),而 WebSocket 是多對象的,即每個(gè)客戶端對應(yīng)后臺的一個(gè) WebSocket 對象,也可以理解成 new 了一個(gè) WebSocket,這樣當(dāng)然是不能獲得自動(dòng)注入的對象了,因?yàn)檫@兩者剛好沖突。
@Autowired 注解注入對象操作是在啟動(dòng)時(shí)執(zhí)行的,而不是在使用時(shí),而 WebSocket 是只有連接使用時(shí)才實(shí)例化對象,且有多個(gè)連接就有多個(gè)對象。
所以我們可以得出結(jié)論,這個(gè) Service 根本就沒有注入到 WebSocket 當(dāng)中。
使用static靜態(tài)變量
讀取nacos的配置,通過Environment來獲取,必須使用static,將需要注入的 Service 改為靜態(tài),讓它屬于當(dāng)前類,然后通過 set方法進(jìn)行注入即可解決。
環(huán)境變量注入
private static Environment environment;
@Autowired
private void setEnvironment(Environment environment){
WebSocketServer.environment = environment;
}
在連接websocket的時(shí)候獲取nacos的字段值
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
try {
token = environment.getProperty("platform.login.token");
String stationIDStr = environment.getProperty("platform.station.id");
if (StrUtil.isEmptyIfStr(stationIDStr)){
stationId = 1;
}else {
stationId = Integer.valueOf(stationIDStr);
}
this.session = session;
this.userId = userId;
webSockets.add(this);
sessionPool.put(userId, session);
log.info("[websocket消息]有新的連接,總數(shù)為:" + webSockets.size());
} catch (Exception e) {
}
}