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");
        }
  • 相关阅读:
    树链剖分 (模板) 洛谷3384
    ST表 (模板) 洛谷3865
    IOI 2005 River (洛谷 3354)
    IOI 2005 River (洛谷 3354)
    poj1094 Sorting It All Out
    poj1094 Sorting It All Out
    spfa(模板)
    HAOI 2006 受欢迎的牛 (洛谷2341)
    HAOI 2006 受欢迎的牛 (洛谷2341)
    洛谷1850(NOIp2016) 换教室——期望dp
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13218050.html
Copyright © 2011-2022 走看看