Template Method and Chain of Responsibility
Mid-level Frequently asked 5 min
On this page
The question
Where does Spring use Template Method and Chain of Responsibility?
30-second answer
Template Method: OncePerRequestFilter has a final doFilter that calls your doFilterInternal, and AbstractApplicationContext.refresh() calls hooks such as onRefresh(). Chain of Responsibility: servlet filters, including Spring Security's filter chain, where each filter calls chain.doFilter or stops the request. JdbcTemplate is a related form: it fixes the JDBC (Java Database Connectivity) steps and takes your code as a callback.
Understand it
A request through a handler chain
Step by stepA POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller.
View as text
Three handlers in a row, Logging, Authentication and Controller, with a request moving through them. Arrows go forward along the top and back along the bottom.
A POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller. The request waits on the left.
Logging notes the request and calls next. Each handler knows only the next one, never the whole chain. Logging is highlighted.
Authentication checks the token. It is valid, so this handler also calls next. Authentication is highlighted.
The last link is the controller. It runs only because every handler before it chose to call next. The controller is highlighted.
The response travels back through the same handlers in reverse, so Logging can also record the 200 status. The request travels back, labelled 200.
A request with no token: Authentication returns 401 and never calls next. The controller does not run, and Logging still sees the response. The controller fades, and a mark reads 401, stopped by Authentication.
Three handlers in a row, Logging, Authentication and Controller, with a request moving through them. Arrows go forward along the top and back along the bottom.
A POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller. The request waits on the left.
Logging notes the request and calls next. Each handler knows only the next one, never the whole chain. Logging is highlighted.
Authentication checks the token. It is valid, so this handler also calls next. Authentication is highlighted.
The last link is the controller. It runs only because every handler before it chose to call next. The controller is highlighted.
The response travels back through the same handlers in reverse, so Logging can also record the 200 status. The request travels back, labelled 200.
A request with no token: Authentication returns 401 and never calls next. The controller does not run, and Logging still sees the response. The controller fades, and a mark reads 401, stopped by Authentication.
Takeaway: Each handler does its job and decides whether to call the next one, so a handler can stop a request before it ever reaches the controller.
Put the filters in order
BuildPut the filters in order so that each one has what it needs. Every position says why it comes where it does.
Drag a piece, or select it and then select a place.
View as text
A vertical chain of five filter positions, joined by arrows from top to bottom. Put the filters in order so that each one has what it needs. Every position says why it comes where it does.
The right order is: Logging, because it must also record rejected requests. Authentication, which works out who is calling. Authorization, which needs to know who, to decide if they may. Validation, which checks the body only for allowed callers. Controller, which runs only if every filter called next.
Who comes before may. Each filter can stop the request with its own status, and only a request that passes all of them reaches the controller. Once solved, each filter that can stop a request shows its status: Authentication 401, Authorization 403 and Validation 400.
A vertical chain of five filter positions, joined by arrows from top to bottom. Put the filters in order so that each one has what it needs. Every position says why it comes where it does.
The right order is: Logging, because it must also record rejected requests. Authentication, which works out who is calling. Authorization, which needs to know who, to decide if they may. Validation, which checks the body only for allowed callers. Controller, which runs only if every filter called next.
Who comes before may. Each filter can stop the request with its own status, and only a request that passes all of them reaches the controller. Once solved, each filter that can stop a request shows its status: Authentication 401, Authorization 403 and Validation 400.
Takeaway: Filter order is logic: logging sees everything, authentication comes before authorization, and validation runs only for callers who are allowed.
In code
abstract class ReportJob {
final String run() { // the template: fixed steps, final
String raw = read();
String body = format(raw);
return afterFormat(body);
}
abstract String read(); // a required step
abstract String format(String raw); // a required step
String afterFormat(String body) { return body; } // a hook: optional override
}
class CsvReportJob extends ReportJob {
@Override String read() { return "a,b"; }
@Override String format(String raw) { return raw.replace(',', ';'); }
}
new CsvReportJob().run(); // "a;b"interface Chain { String proceed(Request request); }
interface Handler { String handle(Request request, Chain next); }
static Chain chainOf(List<Handler> handlers, Function<Request, String> controller) {
Chain chain = controller::apply;
for (int i = handlers.size() - 1; i >= 0; i--) {
Handler handler = handlers.get(i);
Chain next = chain;
chain = request -> handler.handle(request, next);
}
return chain;
}
Handler auth = (request, next) ->
request.token() == null ? "401" : next.proceed(request); // stops the chain// Template Method: final doFilter fixes the steps, and you supply doFilterInternal.
class AuditFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response); // Chain of Responsibility: call next
}
}
// JdbcTemplate fixes the steps too, but takes a callback rather than a subclass.
List<String> names = jdbcTemplate.query("select name from orders", (rs, rowNum) -> rs.getString("name"));Solve it
Run fraud checks cheapest first and stop at the first rejection
A payment passes three fraud checks: a blocklist lookup (1 ms), a velocity check against Redis (5 ms) and a machine learning score (200 ms). Any rejection ends the process. Operations wants to reorder or add checks without a deploy of the payment code.
- Read the requirements as a shape. Ordered handlers, each may stop the flow, and the order is configuration: Chain of Responsibility.
- Define one handler type.
FraudCheck.check(payment)returnsAPPROVEorREJECT. The chain walks the checks and stops at the first rejection. - Order by cost. Cheap checks first, so most fraud is rejected before the 200 ms call.
- Make the order data. In Spring, inject
List<FraudCheck>;@Ordersets the sequence, and a new check is a new bean. - Check. When the blocklist rejects, verify with Mockito that the scoring check was never called.
enum Verdict { APPROVE, REJECT }
interface FraudCheck { Verdict check(Payment payment); }
@Component @Order(1)
class BlocklistCheck implements FraudCheck { // 1 ms; VelocityCheck (5 ms) is @Order(2), ScoreCheck (200 ms) @Order(3)
private final Set<String> blocked;
BlocklistCheck(Set<String> blocked) { this.blocked = blocked; }
public Verdict check(Payment p) { return blocked.contains(p.cardHash()) ? Verdict.REJECT : Verdict.APPROVE; }
}
@Service
class FraudChain {
private final List<FraudCheck> checks; // injected in @Order order
FraudChain(List<FraudCheck> checks) { this.checks = checks; }
Verdict evaluate(Payment payment) {
for (FraudCheck check : checks) {
if (check.check(payment) == Verdict.REJECT) return Verdict.REJECT; // later checks never run
}
return Verdict.APPROVE;
}
}How to answer
- Template Method: a base class fixes the steps, and subclasses fill in some of them.
- Chain of Responsibility: each handler does its part and decides whether to pass the request on.
JdbcTemplateis a concrete class using callbacks, so nothing subclasses it.HttpServlet.service()callingdoGet()is the classic servlet example.
Common mistakes
- Calling
JdbcTemplatea pure Template Method; it uses callbacks, not inheritance. - Thinking every handler in a chain must run; any of them can stop the request.
Follow-up questions
What is the Template Method pattern, and what is its main risk?
A base class defines the steps of an algorithm in a final method and leaves some steps abstract, so subclasses vary the details without changing the order. The risk is inheritance itself: subclasses are tied to the base class, and they can only vary by overriding. If the step could be passed in as an object, Strategy or a callback is usually more flexible.
- Making the template method
finalprotects the order of the steps. - In the JDK (Java Development Kit),
AbstractListneeds onlygetandsize; the rest is built from them. - Many subclass overrides can make the flow hard to follow.
See it in the infographic: A request through a handler chain
Why does the order of filters in a chain matter?
Each filter relies on what ran before it. Authorization needs the identity that authentication found, so reversing them rejects everyone or checks nothing. Logging has to come first to record requests that are later rejected. Validation should come after authorization, so unauthorized callers get no feedback about the body. In Spring, you set the order with @Order or addFilterBefore.
- An early filter that stops a request saves the work of all later ones.
- Authentication answers who you are; authorization answers what you may do.
- Filters also run on the way back, in reverse order.
How is Chain of Responsibility different from Decorator?
They look alike: each object holds the next one and forwards to it. A Decorator always forwards, since its job is to add behavior around a target that always runs. A handler in a chain may stop and return, so the end of the chain might never run. A servlet filter can do both, so ask whether the design expects the call to be stopped.
- Decorator guarantees that the target runs.
- A chain does not guarantee that any given handler runs.
- Chains are usually assembled from configuration, and decorators by the code that uses them.
See it in the infographic: A request through a handler chain
Does every handler in a Chain of Responsibility have to handle the request?
No, and there are two common forms. In the GoF (Gang of Four) form, exactly one handler deals with the request and the others pass it along. In the filter form, every handler does some work and passes it on, and any one can stop it. Servlet filters use the second form.
What is a hook method in Template Method?
A step with a default that does nothing or does something sensible, so a subclass may override it but need not. An abstract step must be implemented. afterFormat(body) returning body unchanged is a hook, and AbstractApplicationContext.onRefresh() is a hook that Spring Boot overrides to create the embedded web server.
Check yourself
Show answers
- Logging and Authentication: Correct. Logging runs first and passes it on, and Authentication stops the request there.
- All three: Incorrect. Authentication never called next, so the controller does not run.
- Only Authentication: Incorrect. Logging comes first in the chain, so it had already run.
Show answers
- Authentication: Correct. Authorization decides what a caller may do, so it needs to know who the caller is.
- The controller: Incorrect. The controller runs last, and only for requests that pass the filters.
- Validation: Incorrect. Validating first would give unauthorized callers feedback about the body.