Spring Boot Best Practices

Chapter 2 · Practice 4 of 4

Fix circular dependencies instead of allowing them

From Structure and dependency injection

Why it matters

Spring Boot prohibits circular references by default, and the startup error lists the cycle. It is tempting to set spring.main.allow-circular-references=true or add @Lazy to make it go away, but a cycle means two classes each need the other, which usually means a responsibility is in the wrong place.

Ways to break a cycle:

  1. Move the shared logic into a third class both can depend on.
  2. Publish an application event instead of calling the other service directly.
  3. Pass the value needed as a method parameter instead of injecting the whole bean.

Cycles only get harder to untangle as more code depends on both classes.