spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.25k stars 37.98k forks source link

Cyclic dependency with constructor injection #26703

Open 1zg12 opened 3 years ago

1zg12 commented 3 years ago

Background

Spring is discouraging use of filed injection, and in favor or constructor injection.

However, when the beans need to cross reference to each other. For example:

class BeanA{
    @Autowired
    public BeanA(BeanB beanB) {
        this.beanB= beanB;
    }
}

class BeanB{
    @Autowired
    public BeanB(BeanA beanA) {
        this.beanA= beanA;
    }

this will instead throw out exception

APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  beanA defined in URL [jar:file:/...class]
↑     ↓
|  beanB defined in URL [jar:file:/....class]
↑     ↓
|  xx (field xx) 

Changes

Instead of just saying "Field injection is not recommended", can we make it clear, by adding

Field injection is not recommended **however, please don't constructor injection with circular reference** ?

?

Related Issues

sbrannen commented 3 years ago

Related issues: