说明:本篇循环依赖单指在IOC容器内的bean之间的循环依赖。
什么是循环依赖?
循环依赖:就是循环引用,就是两个或两个以上的bean之间相互持有对方。比如CircleA引用CircleB,CircleB引用CircleC,CircleC引用CircleA,最终形成一个环,循环调用是无法解决的,除非有终止条件,否则就是死循环,最终导致内存溢出错误。_______《spring源码深度解析》
spring如何解决循环依赖?
1 . 构造器依赖
表示通过构造器注入依赖,该依赖spring无法解决,直接抛出BeanCurrentlyInCreationException异常。
2.setter循环依赖
2.1 scope为singleton (可以解决)
- 创建CircleA.java
public class CircleA {
private CircleB circleB;
public void setCircleB(CircleB circleB) {
this.circleB = circleB;
}
}
- 创建CircleB.java
public class CircleB {
private CircleC circleC;
public void setCircleC(CircleC circleC) {
this.circleC = circleC;
}
}
-
创建CircleC.java
public class CircleC {
private CircleA circleA;
public void setCircleA(CircleA circleA) {
this.circleA = circleA;
}
}
-
创建xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="circleA" class="com.atlwj.demo.ioc.circledependency.CircleA">
<property name="circleB" ref="circleB"></property>
</bean>
<bean id="circleB" class="com.atlwj.demo.ioc.circledependency.CircleB">
<property name="circleC" ref="circleC"></property>
</bean>
<bean id="circleC" class="com.atlwj.demo.ioc.circledependency.CircleC">
<property name="circleA" ref="circleA"></property>
</bean>
</beans>
-
创建Test.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean1.xml");
System.out.println(context.getBean("circleA"));
}
}
- 执行结果
2.2 scope为prototype (无法解决)
-
修改xml文件 (注意:必须是全部修改为prototype范围)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="circleA" class="com.atlwj.demo.ioc.circledependency.CircleA" scope="prototype">
<property name="circleB" ref="circleB"></property>
</bean>
<bean id="circleB" class="com.atlwj.demo.ioc.circledependency.CircleB" scope="prototype">
<property name="circleC" ref="circleC"></property>
</bean>
<bean id="circleC" class="com.atlwj.demo.ioc.circledependency.CircleC" scope="prototype">
<property name="circleA" ref="circleA"></property>
</bean>
</beans>
- 执行结果
结论:对于setter方式完成的依赖注入,spring只会解决bean的scope为singleton单例范围的循环依赖问题(注意:单例bean可以通过setAllowCircularReferences 为false来禁用spring容器对于循环依赖的处理 );prototype多实例范围的循环依赖不会处理(抛出BeanCurrentlyInCreationException异常)。
3.循环依赖原理