• Spring Boot@Component注解下的类无法@Autowired的问题


    springboot 项目 ,突然在@Component注解下@Autowired的类为null的情况,也就是没注入成功,或者说是此类在bean加载之前就被调用了。

    以下是解决办法:

    编写工具类实现ApplicationContextAware接口,重写setApplicationContext方法

    @Component
    public class SpringContextUtil implements ApplicationContextAware {

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

    /*
    * 实现了ApplicationContextAware 接口,必须实现该方法;
    * 通过传递applicationContext参数初始化成员变量applicationContext
    */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
    throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
    return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
    return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {
    return (T) applicationContext.getBean(clazz);
    }

    }

    调用方式:

    在无法引入的类中,通过beanName引入

        public RedisConfig getRedisConfig() {
            return SpringContextUtil.getBean("redisConfig");
        }
  • 相关阅读:
    代码管理模型概况
    循环链表
    队列

    链表
    java 2020-10-12T11:22:49.000+0800 字符串转换成正常时间格式
    动态数组
    mysql练习
    复杂度与LeetCode
    记一次带逗号的数字类型处理
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13218050.html
Copyright © 2020-2023  润新知