使用WebSocket进行依赖注入为null的解决办法

最近需要整合Websocket,@ServerEndpoint注解所标注的类,类似于我们写的@Controller标注的Controller层,

结果@Autowire注入的Service层的bean为null,然后检查配置,各种姿势测试这个bean,发现和

@ServerEndpoint有关。先看代码

@ServerEndpoint(value="/websocket/{userId}")
public class WebSocket {

private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String userId;

这里使用注解@Autowired @Resource 注入结果都为null
private UsersServerImpl usersServerimpl;


@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {

你要用 @ServerEndpoint实现ws,就注定不能用@Autowired注入bean,那咋整?new一个?肯定不行。思来想去,你不就是要个bean么,我@Autowired把你召唤不出来,那我拿spring上下文把你getBean(“name”)一下如何,注解用不了咱原生走一波。

  ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-dao.xml");

UsersServiceImpl usersServiceImpl=(UsersServiceImpl)context.getBean("usersServiceImpl");

Push push = usersServiceImpl.selectPushByName(studentid);

那么问题又来了,容器启动的时候spring上下文已经加载了,怎样拿到这个上下文?​​参考解释​

拿到上下文就好说了,直接getBean就OK。

 @OnClose
public void onClose(){
System.out.println("连接:{} 关闭"+this.userId);

if(this.usersServerimpl == null){
this.usersServerimpl=(UsersServerImpl) SpringContextUtil.getBean("usersServerImpl");
Integer integer = usersServerimpl.signOut(Integer.parseInt(this.userId));
}

System.out.println("执行结束");
removeOnlineCount();
}

好了,这个问题目前来说看起来很好的解决了

这里使用到的SpringContextUtil是一个工具类 代码奉上

package com.spz.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
* 获取spring中的bean对象工具类
* @date 2018-07-23 17:42
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {

/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;


/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

/**
* 获取对象 这里重写了bean方法,起主要作用
*/
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}