做韩国网站,企业网站的作用有哪些,建正建设官方网站,最新备案的网站在websocket中使用ServerEndpoint无法注入Autowired、Value
问题分析
Spring管理采用单例模式#xff08;singleton#xff09;#xff0c;而 WebSocket 是多对象的#xff0c;即每个客户端对应后台的一个 WebSocket 对象#xff0c;也可以理解成 new 了一个 WebSocketServerEndpoint无法注入Autowired、Value
问题分析
Spring管理采用单例模式singleton而 WebSocket 是多对象的即每个客户端对应后台的一个 WebSocket 对象也可以理解成 new 了一个 WebSocket这样当然是不能获得自动注入的对象了因为这两者刚好冲突。
Autowired 注解注入对象操作是在启动时执行的而不是在使用时而 WebSocket 是只有连接使用时才实例化对象且有多个连接就有多个对象。
所以我们可以得出结论这个 Service 根本就没有注入到 WebSocket 当中。
使用static静态变量
读取nacos的配置通过Environment来获取必须使用static将需要注入的 Service 改为静态让它属于当前类然后通过 set方法进行注入即可解决。
private static Environment environment;
Autowired
private void setEnvironment(Environment environment){WebSocketServer.environment environment;
}在连接websocket的时候获取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消息]有新的连接总数为: webSockets.size());} catch (Exception e) {}
}