spring circular reference

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s