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");
        }
  • 相关阅读:
    .net 日期格式化
    grunt 上手
    设计模式的认识
    顺时针打印矩阵
    WCF 框架运行时类图
    Python闭包详解
    软件用了那些技术
    zoj 1610 Count the Colors(线段树延迟更新)
    快速提高自己的技术的办法?有两个方法
    纯win32实现PNG图片透明窗体
  • 原文地址:https://www.cnblogs.com/wiliamzhao/p/13218050.html
Copyright © 2011-2022 走看看