Video in progress
How do you build several validation or processing steps with Chain of Responsibility, and what does that look like in Spring?
Each step is a separate class implementing a common interface; the chain calls them in order, and each step decides whether to "stop" or "continue". In Spring you inject a List<Handler> and set the order with @Order: adding a new step is just adding a new bean.
📖 Answer
For example, fraud checks on a payment request:
public interface PaymentCheck {
Optional<String> reject(PaymentRequest r); // empty means it passed
}
@Component @Order(10)
class AmountLimitCheck implements PaymentCheck {
public Optional<String> reject(PaymentRequest r) {
return r.amount().greaterThan(LIMIT) ? Optional.of("limit") : Optional.empty();
}
}
@Component @Order(20)
class BlacklistCheck implements PaymentCheck { ... }
@Service
class PaymentGuard {
private final List<PaymentCheck> checks; // sorted by @Order
PaymentGuard(List<PaymentCheck> checks) { this.checks = checks; }
public void verify(PaymentRequest r) {
for (var c : checks) {
c.reject(r).ifPresent(reason -> { throw new PaymentRejected(reason); });
}
}
}
This is the same idea as Servlet Filters, the Spring Security filter chain and HandlerInterceptors.
What to watch for:
- if the order matters, state it explicitly: without
@Orderthe order of theListis not guaranteed; - cheap checks first, the ones that call an external service last;
- if you need to "collect all errors" (form validation), don't stop at the first error: gather the results into a list;
- if the chain is long, show which step rejected in the log and in metrics, otherwise it's hard to answer "why was this rejected?" on prod.
How it differs from Strategy: with a strategy one implementation is picked, here they all run one after another.
Sign up to mark studied questions and save your progress.