SteelReed

Search

Search posts, questions…

Spring BootQuestion 4 / 26

Middle

Why prefer constructor injection? How does Spring handle circular dependencies?

Short answer

Constructor injection gives final fields, an object that is valid from the moment it's created, and tests with plain new. With a cycle through constructors Spring can't create either bean first; since Boot 2.6 cycles are forbidden by default, and the right fix is the design.

at startupfix the designOrderServiceneeds PaymentServicePaymentServiceneeds OrderServiceBeanCurrentlyInCreationExceptionSplit a serviceor use events

3 points to say:

  1. Constructor injection: final, valid immediately, explicit dependencies, testable without Spring.
  2. A constructor cycle fails at startup; Boot 2.6+ forbids cycles by default, even with field/setter injection.
  3. Fix it by splitting a service or using events; @Lazy is only a stopgap.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.