websocket中注入springbean实例,@ServerEndpoint标注的类中注入springbean

注入springbean失败,报空指针

Springboot中使用@ServerEndpoint 标注的websocket服务,需要在发送接收消息时,在websocket服务中使用@Autowired注入spingbean,但是…问题来了…在连接后使用时会发现报空指针;

本次记录一下,解决方法

网上搜了一圈,答案都不尽满意,有的说websocket 服务中加入@Component 将服务也注册成一个spring管理的bean, 有的说websocket服务创建的时机在springIOC容器加载之前。但是都没有解决问题;
首先分析一下原因:

发生这个情况的原因,并不是 websocket 实例创建在springIoc容器之前,导致去注入依赖的时候找不到对应的bean; 实际上再websocket实例网ioc容器中放的时候,这个时候,springbean是创建了的,但是websocekt是多实例的,每次建立连接的时候都会创建一个实例,是多实例的,,这就导致在后面有客户端连接创建实例的时候,并不是从ioc容器中获取的,没有给属性再次赋值的动作,导致后续建立连接的时候使用springbean ,空指针的情况;

那么知道了问题产生的原因:

思路大概有两种:

一种是在每次建立连接的时候,给改实例的springbean注入值;
一种是将springbean设置成static属性,这样在每次创建连接的时候,都能公用第一次给类型注入值;一次注入多次使用;

本次使用的第二种,因为第一种有一些隐形的问题,欢迎使用讨论

第一种代码:

**思路:**在每次创建连接的时候,从ioc容器中找到bean实例,给该websocket实例注入值;


@ServerEndpoint("/myWebsocket")
@Component
public class MyWebsocket implements ApplicationContextAware {
    private MySpringBean mySpringBean;
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContextIoc) throws BeansException {
        applicationContext = applicationContextIoc;
    }

    @OnOpen
    public void onOpen(Session session) {
        // 创建连接时
        System.out.println("有客户端连接...");
        MySpringBean bean = applicationContext.getBean(MySpringBean.class);
        this.mySpringBean = bean;
        mySpringBean.printMsg();
    }
}


@Component
public class MySpringBean {


    public void printMsg(){
        System.out.println("hello websocket");
    }

}

在这里插入图片描述

第二种代码:

思路:
重写set方法,给set方法标注@Autowired 这样set方法中的参数值,就会自动去ioc容器中找,然后赋值给静态属性,以后每次都可以使用;
代码如下:


@ServerEndpoint("/myWebsocket")
@Component
public class MyWebsocket {
    private static MySpringBean mySpringBean;

    @Autowired
    public void setMySpringBean(MySpringBean mySpringBean) {
        MyWebsocket.mySpringBean = mySpringBean;
    }

    @OnOpen
    public void onOpen(Session session) {
        // 创建连接时
        System.out.println("static方式 有客户端连接...");
        mySpringBean.printMsg();
    }
}

在这里插入图片描述

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值