之前转的两篇文章都说过java中的循环依赖,现在大概写个代码demo验证下。之前地址:https://blog.csdn.net/u010730870/article/details/102602597,https://blog.csdn.net/u010730870/article/details/102607053。
循环依赖有以下场景:
1.模块间循环依赖,解决:见上边之前;
2.同模块的类间循环依赖:<模型:A依赖B,B依赖C,C依赖A>
(1)构造器声明对象式依赖:无法解决(不管在不在spring环境下)。(原理见上边之前的地址,下边只说代码验证)
public class A {
B b = new B();
}
public class B {
C c = new C();
}
public class C {
A a = new A();
}
<?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="a" class="com.yoyo.dependcycle.A"/>
<bean id="b" class="com.yoyo.dependcycle.B"/>
<bean id="c" class="com.yoyo.dependcycle.C"/>
</beans>
public class ApplicationContextStarter {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:conf/spring/spring-beans.xml");
for (String name : ctx.getBeanDefinitionNames()) {
System.out.println(name);
}
}
}
结果:直接循环依赖导致栈溢出了:
(2)spring中通过set方法注入式依赖:可以通过spring的三级缓存自动解决。(原理见上边之前的地址,下边只说代码验证)
package com.yoyo.dependcycle;
public class A {
B b ;
public void setB(B b) {
this.b = b;
}
}
package com.yoyo.dependcycle;
public class B {
C c ;
public void setC(C c) {
this.c = c;
}
}
package com.yoyo.dependcycle;
public class C {
A a ;
public void setA(A a) {
this.a = a;
}
}
<?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">
<!--spring可以解决循环依赖(set注入方式依赖) -->
<bean id="a" class="com.yoyo.dependcycle.A">
<property name="b" ref="b"/>
</bean>
<bean id="b" class="com.yoyo.dependcycle.B">
<property name="c" ref="c"/>
</bean>
<bean id="c" class="com.yoyo.dependcycle.C">
<property name="a" ref="a"/>
</bean>
</beans>
package com.yoyo.user;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextStarter {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:conf/spring/spring-beans.xml");
for (String name : ctx.getBeanDefinitionNames()) {
System.out.println(name);
}
}
}
结果:spring利用三级缓存解决了类间循环依赖