Spring / Spring7 Intermediate to Advanced Interview questions
How do you troubleshoot a bean that fails to initialize due to a circular dependency?
The first step is reading the BeanCurrentlyInCreationException stack trace carefully - Spring lists the full cycle of bean names it detected, which immediately tells you which beans are involved and, from their constructors, whether the cycle runs through constructor injection (unresolvable automatically) or setter/field injection (normally resolved automatically, so if it's still failing here, something else is interfering, like a BeanPostProcessor needing the bean too early).
@Service public class OrderService { @Lazy public OrderService(PricingService pricingService) { this.pricingService = pricingService; } }
For a genuine constructor-injection cycle, the most common fixes are: annotate one of the constructor parameters with @Lazy so Spring injects a lazily-initialized proxy instead of forcing eager resolution during construction, breaking the deadlock; refactor one side to setter injection so the three-level cache can resolve it; or, often the better long-term fix, extract the shared behavior both beans depend on into a third bean that each can depend on independently, removing the cycle altogether rather than just working around it.
More Related questions...