SpringBoot中WebSocket不能实现注入的问题

33 篇文章 1 订阅
27 篇文章 0 订阅

项目需要长连接业务,我使用SpringBoot中的 ,一切都调得好好的,到对接数据库的时候,一个大坑突然出现:ServerEndpoint中竟然不能实现注入,甚至使用的对象中有注入也不行。找了两天资料,写了好几个demo,有人说在@ServerEndpoint加上, configurator = SpringConfigurator.class,测试不通过;有人说使用 ContextLoader.getCurrentWebApplicationContext(),貌似也不行。甚至尝试过把jpa改成idbc也不行。

后来在https://segmentfault.com/q/1010000010103973这篇文章中找到了突破。

1.首先需要在ServerEndpoint中加上这一部分:

    private static ApplicationContext applicationContext;
    private WsService wsService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        MsgCenter.applicationContext = applicationContext;
    }
2.在onOpen()方法中加入:

wsService = applicationContext.getBean(WsService.class);

3.把SpringBoot的启动类改造成这个样子

public class Application {

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
        MsgCenter.setApplicationContext(configurableApplicationContext);//解决WebSocket不能注入的问题
    }
}

重新运行,在Android的配合下,成功访问数据库,读取到了需要的数据:



  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值