繁体   English   中英

Spring自动装配订单和@PostConstruct

[英]Spring autowiring order and @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被称为


我的问题是如何像上面的场景一样一步一步地进行自动装配?
而如何printMe()的方法beanb被称为不调用其@PostConstruct第一?

下面应该是可能的顺序

  1. beanb开始自动装配
  2. Beanb类初始化期间,beana开始自动装配
  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完成了@PostConstructinit()beanb被调用
  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.

在上面的控制台应用程序中,您尝试自动装配并注入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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM