Java 中如何避免循环引用,解决相互依赖的问题

spring中通过依赖注入的方法来解决类的相互依赖问题!!!

spring中通过依赖注入的方法来解决类的相互依赖问题!!!

spring中通过依赖注入的方法来解决类的相互依赖问题!!!


只要不是构造函数注入就不会产生循环引用的问题。

这是因为:

spring 容器对构造函数配置Bean 进行实例化的时候,有一个前提,即 Bean 构造函数入参引用的对象必须已经准备就绪。

由于这个机制,如果两个Bean 都循环引用,都采用构造函数注入的方式,就会发生类似于线程死锁的循环依赖问题。


代码示例:

public class TestA {

    private TestB b;

    public TestA(){
        b = new TestB();
        System.out.println("init A");
    }

}
public class TestB {

    private TestA a;

    public TestB(){
        a = new TestA();
        System.out.println("testB init");
    }

    public static void main(String[] args) {
        TestA testA = new TestA();
    }
}

运行后日志:

Exception in thread "main" java.lang.StackOverflowError

这中情况会导致堆栈溢出

如果将TestA 稍作如下修改即不会出现报错

public class TestA {

    private TestB b;

    public TestA(){
        System.out.println("init A");
    }
    
    public void setB(TestB b){
        this.b = b;
    }

}

参考:

Spring 依赖注入三种方式的实现,及循环依赖问题的解决(源码+XML配置)

如何解决Java循环依赖的问题

猜你喜欢

转载自blog.csdn.net/u014209205/article/details/102524493