Video in progress
Two services call each other and you have a circular dependency. How would you resolve it with a mediator or events?
First, I won't hide it with allow-circular-references. Usually I move the shared part of the two services into a third class, or write a use case class (a mediator) that coordinates both. If one side only needs to say "something happened", I break the dependency with an event.
📖 Answer
A typical case: OrderService calls PaymentService for payment, and PaymentService calls OrderService on a refund to change the order status. With constructor injection the application won't start. Since Spring Boot 2.6, startup fails by default even with field injection: "The dependencies of some of the beans in the application context form a cycle".
Setting spring.main.allow-circular-references=true or adding @Lazy only hides the problem: the two classes still can't live without each other, and they are hard to test.
The solution depends on the cause of the cycle.
If both services are really parts of one process, use a mediator. The class that knows the process calls both, and they don't know about each other:
@Service
class RefundOrder { // mediator / use case
private final OrderService orders;
private final PaymentService payments;
@Transactional
public void refund(long orderId) {
var order = orders.markRefunding(orderId);
payments.refund(order.paymentId(), order.total());
orders.markRefunded(orderId);
}
}
If one side only needs to notify, use an event. PaymentService publishes a PaymentRefunded event and OrderService listens for it. The dependency becomes one-directional.
Sometimes the cycle exists because of one small method. Moving that method into a separate class that both can use is the cheapest way out.
A mediator has limits too: if you end up with a single OrderManager that knows every service, you have built a god class. A separate small class per use case works better.
Sign up to mark studied questions and save your progress.