首页 > 编程语言 > 详细

Spring Boot@Component注解下的类无法@Autowired的问题

时间:2019-12-04 14:33:30      阅读:327      评论:0      收藏:0      [点我收藏+]

title: Spring Boot@Component注解下的类无法@Autowired的问题
date: 2019-06-26 08:30:03
categories:

  • Spring Boot
    tags:
  • 注入问题

这个问题心累

在把我的一个非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;
    }
}
  • 声明一个此类的静态变量,用以保存bean。
  • 使用@PostConstruct注解,将需要注入的类添加到静态变量中。
  • 接下来,使用这个静态变量来调用注入类就行了。

@PostConstruct这个注解的具体作用就是:

注解在方法上,表示此方法是在Spring实例化该bean之后马上执行此方法,之后才会去实例化其他bean

这样在Spring实例化ComponentClass之后,马上执行此方法,初始化ComponentClass静态对象和成员变量jedisClient

原文地址:https://blog.csdn.net/weixin_38950807/article/details/93709887

Spring Boot@Component注解下的类无法@Autowired的问题

原文:https://www.cnblogs.com/jpfss/p/11981858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!