springboot整合websocket中自动注入null问题

主要原因就是websocket为多实例,而spring默认为单例模式所以注入失败。

解决自己尝试过在自己类中写get方法返回new-对象,单例模式的懒汉式,这种方法可以解决自己写的类注入但是导入的依赖不能。

最后解决方法手写一个spring工具类手动注入:

package com.example.utils;

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

/**
 * @author 07
 * @version 1.0
 * @date 2021/7/30 15:07
 * @description: TODO   spring手动注入工具类 为解决websocket多实例问题,spring默认单例模式
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {
    // Spring应用上下文环境
    private static ApplicationContext applicationContext;
    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     *
     * @param applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }
    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     * 获取对象
     *
     * @param name
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
}

使用方法

MessageDto messageDto = (MessageDto) SpringContextUtil.getBean("messageDto");
原文地址:https://www.cnblogs.com/Zeng02/p/15080224.html