websocket服务中注入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();
}
}