title: Spring Boot@Component注解下的类无法@Autowired的问题
date: 2019-06-26 08:30:03
categories:
在把我的一个非Web程序迁移从Spring
迁移到SpringBoot
时,出现了在@Component
注解下@Autowired
的类为null
的情况,也就是没注入成功,或者说是此类在bean
加载之前就被调用了。
试了各种办法,修改扫描包,修改@Component
注解等等,皆未成功,后来看到了一个方法,探究了一下。
@Component
public class ComponentClass {
@Autowired
private JedisClient jedisClient;
public static ComponentClass componentClass;
@PostConstruct
public void init(){
componentClass = this;
componentClass.jedisClient = this.jedisClient;
}
}
@PostConstruct
注解,将需要注入的类添加到静态变量中。@PostConstruct
这个注解的具体作用就是:
注解在方法上,表示此方法是在Spring
实例化该bean
之后马上执行此方法,之后才会去实例化其他bean
。
这样在Spring
实例化ComponentClass
之后,马上执行此方法,初始化ComponentClass
静态对象和成员变量jedisClient
。
Spring Boot@Component注解下的类无法@Autowired的问题
原文:https://www.cnblogs.com/jpfss/p/11981858.html