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"); }