Spring自动assembly订单和@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(); } } 

我有以下输出:

豆a被称为

打印我在Bean B中调用

beanb被称为

我的问题是如何像上面的场景一样一步一步地进行自动assembly?
如何在不调用@PostConstruct情况下调用printMe()方法?

下面应该是可能的顺序

  1. beanb开始自动assembly
  2. Beanb类初始化期间,beana开始自动assembly
  3. 一旦beana被创建了@PostConstruct即beana的init()被调用
  4. init()System.out.println("bean a is called"); 被叫
  5. 然后是b.printMe(); 被调用导致System.out.println("print me is called in Bean B"); 执行
  6. beana完成了@PostConstructbeanainit()被调用
  7. 然后是System.out.println("beanb is called"); 被叫

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

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

您的答案是正确的,如您在问题中所示。

现在获得符号@Autowired的概念。 在完成类加载后,所有@Autowired对象都被初始化并加载到内存中。

现在这是你的SpringBootApplication

 @SpringBootApplication public class Demo1Application { @Autowired BeanB beanb; // You are trying to autowire a Bean class Named BeanB. 

在上面的控制台应用程序中,您尝试自动assembly并注入BeanB类型的对象。

现在,这是您对BeanB的定义

 @Service public class BeanB { @Autowired private BeanA beana ; 

BeanB类中,您尝试注入类BeanA的Object,它也在您的控制台Project中定义。

因此,在您的Demo1Application中注入类BeanB的Object必须注入类BeanA的Object。 现在首先创建BeanA类对象。

现在,如果你看到你的Class BeanA的定义

  @Service public class BeanA { @Autowired private BeanB b; @PostConstruct // after Creating bean init() will be execute. public void init(){ System.out.println("bean a is called"); b.printMe(); } } 

因此,在注入Object BeanA方法之后,绑定@PostContruct将会执行注释。

所以,执行流程将是……

 System.out.println("bean a is called"); System.out.println("print me is called in Bean B"); System.out.println("beanb is called");