Video in progress

Strong Middle 🧭 Design patterns

A servlet `Filter`, a `HandlerInterceptor` and an AOP aspect all wrap a call. Which job goes where?

A filter works at the servlet level, for every HTTP request, and can wrap and replace the request and response. An interceptor lives inside Spring MVC and knows which controller method will be called. An aspect is independent of HTTP and wraps any bean method.

📖 Answer

All three are the chain/proxy idea, but they sit in different layers and each sees something different.

A filter runs before DispatcherServlet. Static files, error pages and Spring Security are all at this level. It is the only place where you can replace the request or response with a wrapper. Good fits: correlation id and MDC, CORS, gzip, request size limits, body caching.

A HandlerInterceptor runs after the handler has been chosen. In preHandle you get the HandlerMethod, so you can read annotations on the method:

public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
    if (handler instanceof HandlerMethod hm && hm.hasMethodAnnotation(RequiresTariff.class)) {
        return tariffs.allowed(req);   // false — the chain stops
    }
    return true;
}

Good fits: endpoint-specific checks, locale, per-endpoint rate limits. Two traps: postHandle isn't called if an exception is thrown (do cleanup in afterCompletion), and a @ResponseBody response has already been written by the time it reaches postHandle, so to change the body you need a ResponseBodyAdvice.

An aspect works at the level of bean methods. It wraps service methods whether they're called from a Kafka listener or a scheduler. Good fits: per-method metrics, audit, and boundaries like @Transactional. But it doesn't work on self-invocation and knows nothing about the HTTP context.

I ask one question when choosing: is this about HTTP or about a business operation? If HTTP, use a filter or interceptor; if business, use an aspect or plain explicit code.