首先,spring是支持setter循環依賴的,可是不支持基於構造函數的循環依賴注入。一直不太明白其中原理,直到看到官方文檔中的這麼一段話spring
Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken-and-egg scenario).bash
大概意思就是說,對於A和B之間的循環依賴,會強制使另外一個bean注入一個未徹底初始化完成的本身。函數
話很少說,上代碼ui
class A{
public A(){
System.out.println("開始建立a");
}
private B b;
@Autowired
public void setB(B b){
System.out.println("b 被注入!");
this.b=b;
}
@PostConstruct
public void init(){
System.out.println("a 初始化完成!");
}
}
class B{
public B(){
System.out.println("開始建立b");
}
private A a;
@Autowired
public void setA(A a){
System.out.println("a 被注入!");
this.a=a;
}
@PostConstruct
public void init(){
System.out.println("b初始化完成!");
}
}
複製代碼
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.register(A.class);
context.register(B.class);
context.refresh();
複製代碼