SpringBoot中使用websocket遇到的问题

本文介绍了在SpringBoot项目中使用WebSocket遇到的三个主要问题:打包失败、测试类异常以及自动注入失败。针对这些问题,提出了相应的解决策略,包括调整测试类配置以避免依赖容器启动、使用SpringBootTest.WebEnvironment.RANDOM_PORT启动内嵌容器以及解决WebSocket对象与Spring单例冲突的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用websocket打包时失败

在打包时出错: PrivatemsgApplicationTests.contextLoads >> IllegalState Failed to load Applicat…
跳过test 注释掉 runwith(SpringRunner.class)即可成功打包

2、使用websocket后运行测试类抛异常

在配置了ServerEndpointExporter的bean后,运行测试类出现了Error creating bean with name 'serverEndpointExporter
原因是websocket需要依赖tomcat等容器启动。所以在测试的时候需要真正的启动一个tomcat作为容器。
解决方法:
1、将@RunWith(SpringRunner.class) 去掉即可,但是这种方式会有局限,比如下方你要@Authwired一个类的时候会报错

2、在SpringBootTest后加上(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 即可
RANDOM_PORT加载EmbeddedWebApplicationContext,并提供一个真实 的servlet环境。
使用该模式内嵌容器将启动,并监听在一个随机端口。

3、使用websocket内自动注入失败

1、@ServerEndpoint(value="/websocket/{playerId}",configurator = SpringConfigurator.class)
加上configurator 使spring注入可用

2、设置成静态属性用set方法注入
本质原因: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。

3、

在启动类中加上

      ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
      //解决WebSocket不能注入的问题
      MessageController.setApplicationContext(configurableApplicationContext);
//此处是解决无法注入的关键
private static ApplicationContext applicationContext;
//你要注入的service或者dao
private CDSocketMessageService cdSocketMessageService;
public static void setApplicationContext(ApplicationContext applicationContext) {
    MessageController.applicationContext = applicationContext;
}

最后通过applicationContext取出想要注入的bean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值