spring-projects / spring-projects/spring-framework

Cyclic dependency with constructor injection

Open
#26,703 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

in: core type: documentation
Dominant language
Java
Stars
60.2k
Forks
38.8k
Avg merge
5d 2h
Merged PRs (30d)
27

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the application-context startup failure and the circular-dependency diagnostic shown in this issue, then review related issues #25443, #27534, and #30333. Done means the diagnostic clearly warns about constructor injection with circular references without obscuring the existing cycle details.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.