Spring自动装配顺序和@PostConstruct

新手上路,请多包涵

我对 Spring 中的自动接线顺序和 @PostConstruct 逻辑有疑问。例如下面的演示代码我有一个主要的 Spring Boot 类:

 @SpringBootApplication
public class Demo1Application {

    @Autowired
    BeanB beanb;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }
}

和 2 @Service 定义:

 @Service
public class BeanB {

    @Autowired
    private BeanA beana ;

    @PostConstruct
    public void init(){
        System.out.println("beanb is called");
    }

    public void printMe(){
        System.out.println("print me is called in Bean B");
    }
}

@Service
public class BeanA {

    @Autowired
    private BeanB b;

    @PostConstruct
    public void init(){
        System.out.println("bean a is called");
        b.printMe();
    }
}

我有以下输出:

bean a 被称为

在 Bean B 中调用 print me

beanb 被称为

我的问题是自动装配是如何像上面的场景一样一步一步发生的?

以及如何调用 beanb printMe() 的方法而不首先调用其 @PostConstruct

原文由 cacert 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 787
1 个回答

下面应该是可能的顺序

  1. beanb 开始自动装配
  2. Beanb 的类初始化期间,beana 开始自动装配
  3. 一旦创建了 beana,就会调用 beana 的 @PostConstructinit()
  4. 内部 init() , System.out.println("bean a is called"); 被调用
  5. 然后 b.printMe(); 被调用导致 System.out.println("print me is called in Bean B"); 执行
  6. beana 完成了 @PostConstructinit() beanb 被称为—94dc05feadf4afff1f0c40d
  7. 然后 System.out.println("beanb is called"); 被调用

理想情况下,eclipse 中的调试器可以更好地观察到相同的情况。

Spring 参考手册 解释了循环依赖是如何解决的。 beans 首先被实例化,然后相互注入。

原文由 Mudassar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题