引言:循环依赖就是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;
   }
}
                    
View Code

相关文章:

  • 2021-11-26
  • 2021-05-23
  • 2022-12-23
  • 2021-07-17
  • 2022-01-01
  • 2021-11-26
猜你喜欢
  • 2021-05-21
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2021-09-11
  • 2021-05-11
  • 2021-07-11
相关资源
相似解决方案