Websocket @ServerEndpoint不能注入@Autowired

编程入门 行业动态 更新时间:2024-10-08 08:33:37

<a href=https://www.elefans.com/category/jswz/34/1771432.html style=Websocket @ServerEndpoint不能注入@Autowired"/>

Websocket @ServerEndpoint不能注入@Autowired

在websocket中使用@ServerEndpoint无法注入@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) {}
}

更多推荐

Websocket @ServerEndpoint不能注入@Autowired

本文发布于:2023-11-17 15:09:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644828.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Websocket   ServerEndpoint   Autowired

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!