@Component注解下类无法@Autowired
这个问题心累
在把我的一个非Web程序迁移从Spring迁移到SpringBoot时,出现了在@Component注解下@Autowired的类为null的情况,也就是没注入成功,或者说是此类在bean加载之前就被调用了。
试了各种办法,修改扫描包,修改@Component注解等等,皆未成功,后来看到了一个方法,探究了一下。
1 2 3 4 5 6 7 8 9 10 11 |
@Component public class ComponentClass { @Autowired private JedisClient jedisClient; public static ComponentClass componentClass; @PostConstruct public void init(){ componentClass = this ; componentClass.jedisClient = this .jedisClient; } } |
声明一个此类的静态变量,用以保存bean。 使用@PostConstruct注解,将需要注入的类添加到静态变量中。 接下来,使用这个静态变量来调用注入类就行了。
@PostConstruct这个注解的具体作用就是:
注解在方法上,表示此方法是在Spring实例化该bean之后马上执行此方法,之后才会去实例化其他bean。
这样在Spring实例化ComponentClass之后,马上执行此方法,初始化ComponentClass静态对象和成员变量jedisClient。
@Component注解下@Autowired报错
这是由于 Springboot Bean 的加载机制所导致的,具体大家可以去研究源码。
下面是我的解决方案
仅供参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Component public class XxxConfig { // 1 public static XxxConfig xxxConfig ; @Resource private RedisUtil redisUtil; // 2 @PostConstruct public void init() { xxxConfig = this ; xxxConfig.redisUtil = this .redisUtil; }
public boolean test() { // 3.使用 jwtConfig.redisUtil 形式调用 return xxxConfig.redisUtil.set( "abcd" , "123456" , 3600 ); } } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/weixin_38950807/article/details/93709887
查看更多关于关于@Component注解下的类无法@Autowired问题的详细内容...