spring circular reference

Jackie
Mar 22, 2021

--

while spring framework is discouraging use of filed injection, and in preference of constructor injection for example. There is an issue with circular reference.

For example:

class BeanA{

@Autowired

public BeanA(BeanB beanB) {

this.beanB= beanB;

}

}

class BeanB{

@Autowired

public BeanB(BeanA beanA) {

this.beanA= beanA;

}

Field injection would otherwise work. However, with above constructor injection, spring would throw out

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)

The alternative solution if must use constructor binding is to use lazy annotation

class BeanA{

@Autowired

public BeanA(@Lazy BeanB beanB) {

this.beanB= beanB;

}

}

https://github.com/spring-projects/spring-framework/issues/26703

--

--

No responses yet