Chapter 2 · Practice 4 of 4
Fix circular dependencies instead of allowing them
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:
- Move the shared logic into a third class both can depend on.
- Publish an application event instead of calling the other service directly.
- 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.