websocket不能注入,@Autowired为空

在调用websocket发送消息时候,发现通过@Autowired无法注入WebSocketProcess,网上搜寻了下答案,大致原因为spring管理的都是单例(singleton),和 websocket (多对象)相冲突。因为websocket是多实例单线程的,而websocket中的对象在@Autowried时,只有整个项目启动时会注入,而之后新的websocket实例都不会再次注入,故websocket上@Autowried的bean是会为null的

解决方法有两个, 第一:将要注入的 service/Bean 改成 static,就不会为null了。(我没有成功)

这里使用静态,让 service 属于类
    private static WebSocketProcess webSocketProcess;

    @Autowired
    public void setWebSocketProcess(WebSocketProcess webSocketProcess) {
          
   
        CReceiveMsgThread.webSocketProcess = webSocketProcess;
    }

第二:通过SpringContextUtil工具类获取上下文的WebSocketProcess对象,这样就不必再注入WebSocketProcess

SpringContextUtil代码:

@Component
public class SpringContextUtil implements ApplicationContextAware {
          
   

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
          
   
        this.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
          
   
        return applicationContext;
    }

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
          
   
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getDomain(){
          
   
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin(){
          
   
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader("Origin");
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
          
   
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param       <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
          
   
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param       <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
          
   
        return getApplicationContext().getBean(name, clazz);
    }
}
经验分享 程序员 微信小程序 职场和发展