Spring Boot handler interceptors: around every controller call

A HandlerInterceptor runs inside Spring MVC, after the controller method has been chosen, so it can read the method and its annotations. This page explains the callbacks, then runs them for successful, failing, blocked and asynchronous requests, and shows why a header set in postHandle sometimes never reaches the client.

Contents

What a handler interceptor is

A HandlerInterceptor is Spring MVC's hook around controller calls. Once the DispatcherServlet has chosen which handler will serve a request, usually a @RestController method, it runs the interceptors registered for that path before and after the handler. An interceptor can let the request through, stop it, or record what happened.

The interface has three methods, all with default implementations, so you override only the ones you need:

HandlerInterceptor callbacks
MethodWhen it runsTypical use
preHandleBefore the handler; returning false stops the requestAccess checks, rate limits, request context
postHandleAfter the handler returns normally, before the view is renderedAdding model data for HTML views
afterCompletionAfter the response is complete, also after failures, for every interceptor whose preHandle returned trueTiming, metrics, cleanup
afterConcurrentHandlingStartedIn AsyncHandlerInterceptor, when a handler starts asynchronous processingReleasing thread-bound state

Interceptors and servlet filters both wrap requests, but at different levels:

  • Position: filters run outside the DispatcherServlet, interceptors inside it, after the handler has been chosen.
  • Information: an interceptor receives the handler. For a controller method it is a HandlerMethod, which gives the bean, the Method and its annotations. A filter only sees the raw request.
  • Error handling: an exception thrown in preHandle goes through Spring MVC's exception resolvers, so @ExceptionHandler methods can handle it. An exception in a filter cannot reach them.
  • Scope: interceptors only see requests that Spring MVC handles. Requests rejected by a filter, such as Spring Security's, never reach them.

The examples use Spring Boot 4.1 with Spring Framework 7.0 and spring-boot-starter-webmvc. Interceptors are registered in a WebMvcConfigurer; implementing it on the application class keeps each example in one file. The server-side lines are put in a queue and printed after the server has been idle for 300 ms, because afterCompletion may run after the client already has its response.

The life cycle of one request

One interceptor that prints each callback, and five requests that end differently, show when each method runs and when it does not. The requests succeed, fail with a handled exception, fail with an unhandled one, are blocked by preHandle, and ask for a file that does not exist:

Java
package demo.lifecycle;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class InterceptorLifecycle implements WebMvcConfigurer {

    // Server-side lines are queued, because afterCompletion can run after the client
    // already has its response; main prints them once the server has gone quiet.
    static final BlockingQueue<String> LOG = new LinkedBlockingQueue<>();

    static void log(String line) {
        LOG.add(line);
    }

    static void printServerLog() throws InterruptedException {
        String line;
        while ((line = LOG.poll(300, TimeUnit.MILLISECONDS)) != null) {
            System.out.println(line);
        }
    }

    static class TracingInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) {
            String name = handler instanceof HandlerMethod m
                    ? m.getBeanType().getSimpleName() + "." + m.getMethod().getName()
                    : handler.getClass().getSimpleName();
            boolean allow = !request.getRequestURI().endsWith("/blocked");
            log("  preHandle       " + request.getDispatcherType() + " " + name + " -> " + allow);
            if (!allow) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
            return allow;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response,
                               Object handler, ModelAndView modelAndView) {
            log("  postHandle      committed=" + response.isCommitted());
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                    Object handler, Exception ex) {
            log("  afterCompletion status=" + response.getStatus()
                    + ", ex=" + (ex == null ? null : ex.getClass().getSimpleName()));
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TracingInterceptor());
    }

    static class OutOfStockException extends RuntimeException {}

    @RestController
    static class ItemController {
        @GetMapping("/items/{id}")
        public String item(@PathVariable String id) {
            log("  controller      item(" + id + ")");
            return switch (id) {
                case "handled" -> throw new OutOfStockException();
                case "unhandled" -> throw new IllegalStateException("bug");
                default -> "item " + id;
            };
        }

        @ExceptionHandler
        public ResponseEntity<String> outOfStock(OutOfStockException e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("out of stock");
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(InterceptorLifecycle.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (String path : new String[] {"/items/7", "/items/handled", "/items/unhandled",
                                             "/items/blocked", "/missing.txt"}) {
                System.out.println("GET " + path);
                HttpResponse<String> r = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        BodyHandlers.ofString());
                printServerLog();
                System.out.println("  client received " + r.statusCode());
            }
        }
    }
}
Output
GET /items/7
  preHandle       REQUEST ItemController.item -> true
  controller      item(7)
  postHandle      committed=true
  afterCompletion status=200, ex=null
  client received 200
GET /items/handled
  preHandle       REQUEST ItemController.item -> true
  controller      item(handled)
  afterCompletion status=409, ex=null
  client received 409
GET /items/unhandled
  preHandle       REQUEST ItemController.item -> true
  controller      item(unhandled)
  afterCompletion status=200, ex=IllegalStateException
  preHandle       ERROR BasicErrorController.error -> true
  postHandle      committed=true
  afterCompletion status=500, ex=null
  client received 500
GET /items/blocked
  preHandle       REQUEST ItemController.item -> false
  client received 403
GET /missing.txt
  preHandle       REQUEST ResourceHttpRequestHandler -> true
  afterCompletion status=404, ex=null
  preHandle       ERROR BasicErrorController.error -> true
  postHandle      committed=true
  afterCompletion status=404, ex=null
  client received 404
  • For /items/7, all three callbacks ran in order around the controller. The handler was the HandlerMethod for ItemController.item.
  • For /items/handled, the controller threw and its own @ExceptionHandler returned 409. postHandle did not run, because the handler did not return normally. afterCompletion received ex=null, since the exception was resolved. An interceptor that counts failures from the ex argument misses every handled exception; read response.getStatus() instead.
  • For /items/unhandled, afterCompletion received the IllegalStateException, while the status was still 200. Tomcat then forwarded to /error, and the interceptor ran a second time, with dispatcher type ERROR, around BasicErrorController.error.
  • For /items/blocked, preHandle set 403 and returned false. Neither the controller nor any other callback of that interceptor ran.
  • For /missing.txt, the handler was a ResourceHttpRequestHandler, Spring's handler for static files, not a HandlerMethod. A cast to HandlerMethod without the instanceof check would have thrown ClassCastException here.
  • postHandle saw committed=true in every case where it ran: the response had already been sent. The section on headers below shows why that matters.

Interceptors run on error dispatches by default, unlike Spring Boot's filter registrations. To skip them, exclude the error path with excludePathPatterns("/error"), or check request.getDispatcherType().

Paths, order and annotations

Real applications register several interceptors with different scopes. Here an audit interceptor covers everything except the health check, and a role check covers only /admin/**. The role check reads a custom @RequiresRole annotation from the controller method, which is something a filter cannot do:

Java
package demo.order;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class OrderAndPaths implements WebMvcConfigurer {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface RequiresRole {
        String value();
    }

    static final BlockingQueue<String> LOG = new LinkedBlockingQueue<>();

    // Prints every callback, so the nesting of two interceptors is visible
    static class Named implements HandlerInterceptor {
        final String name;

        Named(String name) {
            this.name = name;
        }

        @Override
        public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object h)
                throws Exception {
            LOG.add("  " + name + ".preHandle");
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest req, HttpServletResponse res, Object h,
                               ModelAndView mv) {
            LOG.add("  " + name + ".postHandle");
        }

        @Override
        public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
                                    Object h, Exception ex) {
            LOG.add("  " + name + ".afterCompletion");
        }
    }

    // Reads an annotation from the controller method that is about to run
    static class RoleCheck extends Named {
        RoleCheck() {
            super("RoleCheck");
        }

        @Override
        public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object h)
                throws Exception {
            super.preHandle(req, res, h);
            if (h instanceof HandlerMethod method) {
                RequiresRole rule = method.getMethodAnnotation(RequiresRole.class);
                if (rule != null && !rule.value().equals(req.getHeader("X-Role"))) {
                    LOG.add("  RoleCheck rejects: needs " + rule.value());
                    res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return false;
                }
            }
            return true;
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new Named("Audit"))
                .excludePathPatterns("/health")
                .order(1);
        registry.addInterceptor(new RoleCheck())
                .addPathPatterns("/admin/**")
                .order(2);
    }

    @RestController
    static class Endpoints {
        @GetMapping("/health")
        public String health() {
            LOG.add("  controller health");
            return "up";
        }

        @GetMapping("/admin/users")
        public String users() {
            LOG.add("  controller users");
            return "users";
        }

        @GetMapping("/admin/reports/{year}")
        @RequiresRole("auditor")
        public String report() {
            LOG.add("  controller report");
            return "report";
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(OrderAndPaths.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            String[][] calls = {{"/health", "-"}, {"/admin/users", "-"},
                                {"/admin/reports/2026", "-"}, {"/admin/reports/2026", "auditor"}};
            for (String[] call : calls) {
                System.out.println("GET " + call[0] + "  X-Role: " + call[1]);
                HttpResponse<String> r = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + call[0]))
                        .header("X-Role", call[1]).build(), BodyHandlers.ofString());
                String line;
                while ((line = LOG.poll(300, TimeUnit.MILLISECONDS)) != null) {
                    System.out.println(line);
                }
                System.out.println("  client received " + r.statusCode());
            }
        }
    }
}
Output
GET /health  X-Role: -
  controller health
  client received 200
GET /admin/users  X-Role: -
  Audit.preHandle
  RoleCheck.preHandle
  controller users
  RoleCheck.postHandle
  Audit.postHandle
  RoleCheck.afterCompletion
  Audit.afterCompletion
  client received 200
GET /admin/reports/2026  X-Role: -
  Audit.preHandle
  RoleCheck.preHandle
  RoleCheck rejects: needs auditor
  Audit.afterCompletion
  client received 403
GET /admin/reports/2026  X-Role: auditor
  Audit.preHandle
  RoleCheck.preHandle
  controller report
  RoleCheck.postHandle
  Audit.postHandle
  RoleCheck.afterCompletion
  Audit.afterCompletion
  client received 200
  • /health ran with no interceptor at all: the audit interceptor excludes it, and the role check only includes /admin/**.
  • For /admin/users, the preHandle calls ran in registration order, Audit then RoleCheck, and postHandle and afterCompletion ran in reverse order. Interceptors nest like filters: the first in is the last out.
  • The users method has no @RequiresRole, so getMethodAnnotation returned null and the role check let the request through.
  • The report method needs auditor. Without that role, RoleCheck set 403 and returned false. Spring then called afterCompletion only on Audit, the interceptor whose preHandle had already returned true. RoleCheck's own afterCompletion did not run.
  • With X-Role: auditor, the full sequence ran again and the report was returned.

The path patterns use Spring's PathPattern syntax: /admin/** matches any depth, /admin/* one segment, and {year} any single segment. order() sets the position explicitly; without it, interceptors run in the order they were added. For real access control, prefer Spring Security's method security, which also covers code called outside of HTTP; an interceptor like this one suits simpler checks such as feature flags or tenant rules.

Why headers set in postHandle can disappear

postHandle looks like the natural place to add a header to every response, but for REST controllers the body is often written before it runs. The program sets a header in each of three places and calls three endpoints: a small JSON record, a plain string, and a JSON record of about 12 KB:

Java
package demo.posthandle;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@SpringBootApplication
public class PostHandleHeaders implements WebMvcConfigurer {

    static class HeaderInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object h) {
            res.setHeader("X-Pre", "set in preHandle");
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest req, HttpServletResponse res, Object h,
                               ModelAndView mv) {
            LOG.add("  postHandle sees committed=" + res.isCommitted());
            res.setHeader("X-Post", "set in postHandle");
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HeaderInterceptor());
    }

    public record Price(String amount, String currency) {}

    static final BlockingQueue<String> LOG = new LinkedBlockingQueue<>();

    // Runs after the controller returns, but before the body is written
    @RestControllerAdvice
    static class EnvelopeAdvice implements ResponseBodyAdvice<Object> {
        @Override
        public boolean supports(MethodParameter returnType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
            return true;
        }

        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                      MediaType contentType,
                                      Class<? extends HttpMessageConverter<?>> converterType,
                                      ServerHttpRequest request, ServerHttpResponse response) {
            response.getHeaders().set("X-Advice", "set in ResponseBodyAdvice");
            return body;   // could also replace or wrap the body
        }
    }

    @RestController
    static class PriceController {
        @GetMapping("/price")
        public Price price() {
            return new Price("12.50", "EUR");
        }

        @GetMapping("/text")
        public String text() {
            return "12.50 EUR";
        }

        @GetMapping("/big")
        public Price big() {
            return new Price("12.50", "EUR".repeat(4000));   // about 12 KB of JSON
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(PostHandleHeaders.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (String path : new String[] {"/price", "/text", "/big"}) {
                HttpResponse<String> r = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        BodyHandlers.ofString());
                System.out.println("GET " + path + " -> " + r.statusCode() + ", "
                        + r.body().length() + " chars of " + r.headers()
                                .firstValue("Content-Type").orElse("?"));
                String line;
                while ((line = LOG.poll(300, TimeUnit.MILLISECONDS)) != null) {
                    System.out.println(line);
                }
                for (String h : new String[] {"X-Pre", "X-Advice", "X-Post"}) {
                    System.out.println("  " + h + ": "
                            + r.headers().firstValue(h).orElse("(missing)"));
                }
            }
        }
    }
}
Output
GET /price -> 200, 35 chars of application/json
  postHandle sees committed=false
  X-Pre: set in preHandle
  X-Advice: set in ResponseBodyAdvice
  X-Post: set in postHandle
GET /text -> 200, 9 chars of text/plain;charset=UTF-8
  postHandle sees committed=true
  X-Pre: set in preHandle
  X-Advice: set in ResponseBodyAdvice
  X-Post: (missing)
GET /big -> 200, 12032 chars of application/json
  postHandle sees committed=true
  X-Pre: set in preHandle
  X-Advice: set in ResponseBodyAdvice
  X-Post: (missing)
  • The header from preHandle arrived in all three responses, because nothing had been written when it was set.
  • The header from the ResponseBodyAdvice also arrived in all three. beforeBodyWrite runs after the controller returns and just before the converter writes the body, which is the right moment for headers that depend on the result. The same method can change or wrap the body.
  • The header from postHandle arrived only for the small JSON response, where the response was not yet committed. For the plain string, the string converter had already flushed the response. For the 12 KB JSON, the body was larger than Tomcat's 8 KB output buffer, so part of it, with the headers, had already been sent.

The result depends on the converter and on the size of the body, so code that works in a test with a small response can fail in production. For @ResponseBody methods, use postHandle for nothing that changes the response. Set headers in preHandle, in a ResponseBodyAdvice, or in a filter before the chain runs.

Asynchronous requests

A controller that returns a CompletableFuture, a DeferredResult or a Callable frees the Tomcat thread while the result is computed. The request is then dispatched twice, and interceptors see both dispatches. The future here completes after 500 ms on a timer thread:

Java
package demo.async;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class AsyncRequests implements WebMvcConfigurer {

    static final BlockingQueue<String> LOG = new LinkedBlockingQueue<>();

    static class TimingInterceptor implements AsyncHandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object h) {
            LOG.add("  preHandle                       " + req.getDispatcherType());
            return true;
        }

        @Override
        public void afterConcurrentHandlingStarted(HttpServletRequest req,
                                                   HttpServletResponse res, Object h) {
            LOG.add("  afterConcurrentHandlingStarted  " + req.getDispatcherType()
                    + " (Tomcat thread is released)");
        }

        @Override
        public void postHandle(HttpServletRequest req, HttpServletResponse res, Object h,
                               ModelAndView mv) {
            LOG.add("  postHandle                      " + req.getDispatcherType());
        }

        @Override
        public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
                                    Object h, Exception ex) {
            LOG.add("  afterCompletion                 " + req.getDispatcherType());
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TimingInterceptor());
    }

    @RestController
    static class QuoteController {
        @GetMapping("/quote")
        public CompletableFuture<String> quote() {
            LOG.add("  controller returns a future");
            return CompletableFuture.supplyAsync(() -> {
                LOG.add("  future completes on another thread");
                return "EUR/USD 1.09";
            }, CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS));
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(AsyncRequests.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpResponse<String> r = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
                    URI.create("http://localhost:" + port + "/quote")).build(),
                    BodyHandlers.ofString());
            System.out.println("GET /quote");
            String line;
            while ((line = LOG.poll(300, TimeUnit.MILLISECONDS)) != null) {
                System.out.println(line);
            }
            System.out.println("  client received " + r.statusCode() + " " + r.body());
        }
    }
}
Output
GET /quote
  preHandle                       REQUEST
  controller returns a future
  afterConcurrentHandlingStarted  REQUEST (Tomcat thread is released)
  future completes on another thread
  preHandle                       ASYNC
  postHandle                      ASYNC
  afterCompletion                 ASYNC
  client received 200 EUR/USD 1.09
  • On the first dispatch, preHandle ran, the controller returned the future, and Spring called afterConcurrentHandlingStarted instead of postHandle and afterCompletion. The Tomcat thread then went back to the pool.
  • When the future completed, Spring dispatched the request again with type ASYNC to write the result. preHandle ran a second time, followed by postHandle and afterCompletion.
  • Code in preHandle that starts a timer or increments a counter therefore runs twice for one request. Check request.getDispatcherType(), or keep such code in a OncePerRequestFilter, which skips the second dispatch by default.

Implement AsyncHandlerInterceptor when preHandle puts something on the thread, such as a ThreadLocal value or a logging context. afterConcurrentHandlingStarted is then the place to remove it, because the thread will serve other requests while this one waits.

Traps with interceptors

  • Creating with new: an interceptor built with new in addInterceptors is not a Spring bean, so it gets no injected dependencies. To inject services, declare it as a bean and pass the bean to addInterceptor.
  • Replacing Spring Boot's MVC setup: adding @EnableWebMvc turns off Spring Boot's MVC auto-configuration, including its message converters and static resources. Implement WebMvcConfigurer without @EnableWebMvc to add interceptors.
  • Static resources and CORS: interceptors also run for static files and for CORS preflight requests. A preHandle that requires a login header rejects preflights, which browsers send without credentials; skip requests where CorsUtils.isPreFlightRequest(request) is true.
  • Returning false without a response: preHandle that returns false without setting a status sends 200 with an empty body. Always set the status, and a body if the client needs one.
  • Exceptions from preHandle: throwing is often cleaner than returning false, because the exception goes through your @RestControllerAdvice and produces the same error format as the rest of the API.

Choosing between interceptors, filters and advice

Where to put request-wide logic
NeedUse
Logic that depends on the controller method or its annotationsHandlerInterceptor.preHandle
Timing or metrics per handlerpreHandle plus afterCompletion, reading the status, not ex
Headers or body changes for @ResponseBody resultsResponseBodyAdvice
Model attributes for HTML viewspostHandle, or @ModelAttribute in an advice
Thread-bound state with async controllersAsyncHandlerInterceptor
Every request, including ones Spring MVC never handlesA servlet filter
AuthenticationSpring Security
Turning exceptions into responses@RestControllerAdvice

An interceptor is the right tool when the decision needs to know which controller method will run. For the controllers themselves, see Spring Boot @RestController.