Skip to content

Cyclic dependency with constructor injection #26703

Open
@1zg12

Description

@1zg12

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)type: documentationA documentation task

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions