首先,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();
复制代码