问题描述
我对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
公共类BeanB {
@Autowired
私人BeanA beana;
@PostConstruct
public void init(){
System.out.println(beanb called);
}
public void printMe(){
System.out.println(打印我在Bean B中调用);
}
}
@Service
公共类BeanA {
@Autowired
私有BeanB b;
@PostConstruct
public void init(){
System.out.println(bean a被称为);
b.printMe();
}
}
我有以下输出:
我的问题是如何进行自动装配步骤像上面的场景一样步骤?
如何调用 printMe()
beanb
的方法没有先调用它的 @PostConstruct
?
下面应该是可能的顺序
-
beanb
开始自动装配 - 在
Beanb
的类初始化期间,beana开始自动装配 - 一旦beana被创建,
@PostConstruct
ieinit()
beana被调用 - 内部
init()
,System.out.println(bean a被称为);
被调用 - 然后
b.printMe调用();
导致System.out.println(打印我在Bean B中调用);
执行 - 让
beana
完成@PostConstruct
即init()
ofbeanb
被调用 - 然后
System.out.println(beanb is调用);
调用
理想情况下,eclipse中的调试器可以更好地观察到相同的情况。 / p>
解释了如何解析循环依赖关系。首先实例化bean,然后相互注入。
I have a question about auto-wiring order and @PostConstruct
logic in Spring. For example following demo code I have a main Spring Boot class:
@SpringBootApplication
public class Demo1Application {
@Autowired
BeanB beanb;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
and 2 @Service
Definitions:
@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();
}
}
and I have the following output:
My question is how autowiring takes place step by step like a scenario above?
And how printMe()
method of beanb
is called without calling its @PostConstruct
first?
Below should be possible sequence
beanb
starts to get autowired- During class initialization of
Beanb
, beana starts to get autowired - Once beana gets created the
@PostConstruct
i.e.init()
of beana gets called - Inside
init()
,System.out.println("bean a is called");
gets called - Then
b.printMe();
gets called causingSystem.out.println("print me is called in Bean B");
to execute - Having the
beana
completed the@PostConstruct
i.e.init()
ofbeanb
gets called - Then
System.out.println("beanb is called");
gets called
Ideally the same can be better observed by a debugger in eclipse.
The Spring reference manual explains how circular dependencies are resolved. The beans are instantiated first, then injected into each other.
这篇关于Spring自动装配订单和@PostConstruct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!