Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

@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.

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.

question from:https://stackoverflow.com/questions/66062428/field-based-and-constructor-based-circular-dependency-in-spring-boot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
117 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...