首先,spring是支持setter循环依赖的,但是不支持基于构造函数的循环依赖注入。一直不太明白其中原理,直到看到官方文档中的这么一段话
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).
大概意思就是说,对于A和B之间的循环依赖,会强制使另一个bean注入一个未完全初始化完成的自己。
话不多说,上代码
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(); 复制代码