引言:循环依赖就是N个类中循环嵌套引用,如果在日常开发中我们用new 对象的方式发生这种循环依赖的话程序会在运行时一直循环调用,直至内存溢出报错。下面说一下Spring是如果解决循环依赖的。
第一种:构造器参数循环依赖
Spring容器会将每一个正在创建的Bean 标识符放在一个“当前创建Bean池”中,Bean标识符在创建过程中将一直保持在这个池中。
因此如果在创建Bean过程中发现自己已经在“当前创建Bean池”里时将抛出BeanCurrentlyInCreationException异常表示循环依赖;而对于创建完毕的Bean将从“当前创建Bean池”中清除掉。
首先我们先初始化三个Bean。
public class StudentA{ private StudentB studentB; public void setStudentB(StudentBstudentB){ this.studentB=studentB; } publicStudentA(){ } public StudentA(StudentBstudentB){ this.studentB=studentB; } } public class StudentB{ private StudentC studentC; public void setStudentC(StudentCstudentC){ this.studentC=studentC; } publicStudentB(){ } public StudentB(StudentCstudentC){ this.studentC=studentC; } } public class StudentC{ private StudentA studentA; public void setStudentA(StudentAstudentA){ this.studentA=studentA; } publicStudentC(){ } public StudentC(StudentAstudentA){ this.studentA=studentA; } }