spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Cyclic dependency with constructor injection

Open 1zg12 opened this issue 4 years ago • 1 comments

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

  • #25443
  • #27534
  • #30333

1zg12 avatar Mar 19 '21 08:03 1zg12

Related issues:

  • #25443
  • #27534

sbrannen avatar Mar 19 '21 13:03 sbrannen