Avoid Spring circular references and over-eager type matching using lazy initialization

2 min read >

Avoid Spring circular references and over-eager type matching using lazy initialization

Engineering Insights & Enterprise solutions

Circular dependencies between beans managed by Spring are usually caused by a logic error, but it may be sometimes exactly what developers intend to obtain.

We recently ran into this problem: Spring seems to “over-eagerly” initialize the beans, resulting in a circular dependency error.

2007-04-05 13:24:41,310 ERROR [main] context.ContextLoader (ContextLoader.java:205) – Context initialization failed
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘articleManager’: Bean with name ‘*********’ has been injected into other beans [******, **********, **********, **********] 

In its raw version as part of a circular reference, but has eventually been wrapped (for example as part of auto-proxy creation). This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching – consider using ‘getBeanNamesOfType’ with the ‘allowEagerInit’ flag turned off, for example.

We managed to overcome the problem by using the “lazy-init” attribute for our Spring beans. Other techniques for avoiding/fixing the problems are described by Costin Leau and Andreas Senft on the spring framework’s forums here and here.

Unlock innovation and digital transformation for your business.

Get in touch

We are always happy to talk

Phone

+40-21-223-7700

Email

hello@tremend.com

Address

165 Splaiul Unirii, Timpuri Noi Square,
TN Office 2 building, 4th floor,
District 3, Bucharest, Romania, 030134