zoukankan      html  css  js  c++  java
  • 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");
        }
  • 相关阅读:
    【ARTS】打卡第七周
    【ARTS】打卡第六周
    【ARTS】打卡第五周
    【leetcode】 438. Find All Anagrams in a String
    【ARTS】打卡第四周
    【ARTS】打卡第三周
    【leetcode】 11. Container With Most Water
    【ARTS】打卡第二周
    【ARTS】打卡第一周
    深度VS广度——谈谈对测试职业的一些思考
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13218050.html
Copyright © 2011-2022 走看看