@Autowired 在Listener和Filter中注入为null的解决方法

@Autowired注入为null的几种情况

1.在应用的Filter或Listener中使用了@Autowired ,

原因:因为Filter和Listener加载顺序优先于spring容器初始化实例,所以使用@Autowired肯定为null了~~

解决:用ApplicationContext根据bean名称(注意名称为实现类而不是接口)去获取bean,随便写个工具类即可

2.你写的代码有问题,没加@Service注解等 ,这一类低级错误自己检查即可

3.你写的@Service、@Componet、@Configuration、@Repository等Spring注解未被扫描到。

springboot手动手动注入bean

1.SpringBeanUtil 工具类初始化ApplicationContext applicationContext

@Component
public class SpringBeanUtil implements ApplicationContextAware {
    //ApplicationContext对象是Spring开源框架的上下文对象实例,在项目运行时自动装载Handler内的所有信息到内存。
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBeanUtil.applicationContext == null) {
        	SpringBeanUtil.applicationContext = applicationContext;
        }
    }
    
    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    
    //通过class获取Bean.
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }
    
    //通过name,以及Clazz返回指定的Bean
    public static  T getBean(String name, Class clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
    
}

2.获取bean

textAuthorituRemoteApi zkxtAuthorituRemoteApi = SpringBeanUtil.getBean(textAuthorituRemoteApi .class);

本文参考一下文章
https://blog.csdn.net/u013189824/article/details/91579230
https://blog.csdn.net/Sadlay/article/details/82952163

你可能感兴趣的:(spring,boot,spring,java,spring,boot)