Video in progress
If a circular dependency appears between classes or packages, how do you detect and break it?
A circular dependency is when A depends on B and B depends on A. Such modules can't be understood, tested or split apart on their own. You break it by moving the interface to the side that uses it, extracting the shared part into a third module, or using events.
📖 Answer
Since Spring Boot 2.6, a bean cycle with constructor injection fails at startup by default (The dependencies of some of the beans form a cycle). Many people "fix" it with spring.main.allow-circular-references=true or @Lazy, which hides the symptom while the design problem stays.
Detecting cycles at the package level:
- ArchUnit:
slices().matching("com.app.(*)..").should().beFreeOfCycles(); - IntelliJ: Analyze → Dependency Matrix;
- jdeps, or splitting into Gradle/Maven modules, where the compiler doesn't allow a cycle.
Ways to break it:
-
Dependency inversion.
order→useranduser→order(to check the orders when a user is deleted). Declare aUserDeletionGuardinterface in theuserpackage and haveorderimplement it. Now there is onlyorder→user. -
An event.
UserServicepublishes aUserDeletedevent, and theordermodule subscribes to it. -
Extracting the shared part. Move types both use, like
MoneyandUserId, into ashared-kernel. -
Rethinking responsibilities. Often a cycle means one class is doing the work of two modules, and it should be split.
A cycle at the class level (two services call each other) usually shows that a third, higher-level orchestrator is missing: let CheckoutService call both, and they won't know about each other.
Sign up to mark studied questions and save your progress.