其他分享
首页 > 其他分享> > Spring Bean 循环依赖

Spring Bean 循环依赖

作者:互联网

有如下三个类相互依赖

public class StudentA {
 
    private StudentB studentB ;
 
    public void setStudentB(StudentB studentB) {
        this.studentB = studentB;
    }
 
    public StudentA() {
    }
    
    public StudentA(StudentB studentB) {
        this.studentB = studentB;
    }
}

public class StudentB {
 
    private StudentC studentC ;
 
    public void setStudentC(StudentC studentC) {
        this.studentC = studentC;
    }
    
    public StudentB() {
    }
 
    public StudentB(StudentC studentC) {
        this.studentC = studentC;
    }
}

public class StudentC {
 
    private StudentA studentA ;
 
    public void setStudentA(StudentA studentA) {
        this.studentA = studentA;
    }
 
    public StudentC() {
    }
 
    public StudentC(StudentA studentA) {
        this.studentA = studentA;
    }
}

1、构造器循环依赖

 <bean id="a" class="com.zfx.student.StudentA">
		<constructor-arg index="0" ref="b"></constructor-arg>
	</bean>
	<bean id="b" class="com.zfx.student.StudentB">
		<constructor-arg index="0" ref="c"></constructor-arg>
	</bean>
	<bean id="c" class="com.zfx.student.StudentC">
		<constructor-arg index="0" ref="a"></constructor-arg>
	</bean> 

测试类:

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
        System.out.println(context.getBean("a", StudentA.class));
    }
}

结果会抛出BeanCurrentlyInCreationException异常。

2、setter循环依赖

<!--scope="singleton"(默认就是单例方式)  -->
	<bean id="a" class="com.zfx.student.StudentA" scope="singleton">
		<property name="studentB" ref="b"></property>
	</bean>
	<bean id="b" class="com.zfx.student.StudentB" scope="singleton">
		<property name="studentC" ref="c"></property>
	</bean>
	<bean id="c" class="com.zfx.student.StudentC" scope="singleton">
		<property name="studentA" ref="a"></property>
	</bean>

测试类:

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
        System.out.println(context.getBean("a", StudentA.class));
    }
}

结果为:

com.zfx.student.StudentA@1fbfd6

三、解决方案

Spring针对Bean之间的循环依赖,有自己的处理方案。关键点就是三级缓存。当然这种方案不能解决所有的问题,他只能解决Bean单例模式下非构造函数的循环依赖。

提前暴露未实例化的Bean

标签:依赖,Spring,class,studentA,Bean,studentC,studentB,StudentA,public
来源: https://blog.csdn.net/johnllllll/article/details/99243626