我对 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 许可协议
下面应该是可能的顺序
beanb
开始自动装配Beanb
的类初始化期间,beana 开始自动装配@PostConstruct
即init()
init()
,System.out.println("bean a is called");
被调用b.printMe();
被调用导致System.out.println("print me is called in Bean B");
执行beana
完成了@PostConstruct
即init()
beanb
被称为—94dc05feadf4afff1f0c40dSystem.out.println("beanb is called");
被调用理想情况下,eclipse 中的调试器可以更好地观察到相同的情况。
Spring 参考手册 解释了循环依赖是如何解决的。 beans 首先被实例化,然后相互注入。