解决循环依赖(代码验证)

之前转的两篇文章都说过java中的循环依赖,现在大概写个代码demo验证下。之前地址:https://blog.csdn.net/u010730870/article/details/102602597https://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利用三级缓存解决了类间循环依赖

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值