简体   繁体   English

Spring 引导中基于字段和基于构造函数的循环依赖

[英]Field based and Constructor based Circular dependency in Spring boot

@Component 
public class RandomA {
    
    @Autowired
    public RandomB randB;
    
    public RandomA()
    {
        System.out.println("Bello");
    }
    
    public void get()
    {
        System.out.println("AAA");
    }
    

}
@Component
public class RandomB {
    
    public RandomB()
    {
        System.out.println("Hello");
    }
    
     @Autowired
    public RandomA randA;
     
     public void get()
        {
            System.out.println("BBB");
        }
}

I was expecting the above code to give a circular dependency error in spring boot but it executes fine without any error.我期待上面的代码在 spring 引导中给出循环依赖错误,但它执行得很好,没有任何错误。

On the other side:另一方面:

@Component  
public class RandomA {
    
    public RandomB randB;
    
    public RandomA(RandomB randB)
    {
        this.randB=randB;
        System.out.println("Bello");
    }
    
    
    public void get()
    {
        System.out.println("AAA");
    }
}
@Component
public class RandomB {
    
    @Autowired
    public RandomB(RandomA randA)
    {
        this.randA=randA;
        System.out.println("Hello");
    }
    
    public RandomA randA;
    
     public void get()
        {
            System.out.println("BBB");
        }
}

This code leads to circular dependency error.此代码导致循环依赖错误。

Can anyone explain why the 1st one don't lead to circular dependency?/谁能解释为什么第一个不会导致循环依赖?/

Thank you.谢谢你。

In the second example you have the constructor injection, so in case of circular dependency it should fail.在第二个示例中,您有构造函数注入,因此在循环依赖的情况下它应该会失败。 In the first example you use autowiring so dependencies will be injected when they are needed and not on the context loading.在第一个示例中,您使用自动装配,因此依赖项将在需要时注入,而不是在上下文加载时注入。

More details here: https://www.baeldung.com/circular-dependencies-in-spring更多详细信息: https://www.baeldung.com/circular-dependencies-in-spring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM