Which Executes First in Spring Boot: Filter, Interceptor, or AOP?
The article explains the exact execution order of Spring Boot's Filter, Interceptor, and AOP layers, details the nine‑step request lifecycle, clarifies sorting rules, outlines common pitfalls, and provides guidance on choosing the right component for specific scenarios.
Execution Order and Layer Essence
Filter, Interceptor, and AOP belong to three distinct technical layers—Servlet container, Spring MVC, and Spring Bean proxy. The lower the layer, the earlier it runs; the higher the layer, the later it runs.
Filter (Servlet layer) → Interceptor (Spring MVC layer) → AOP (Spring Bean proxy layer) → Controller method
When the response returns, the order is exactly reversed.
Controller return → AOP after/return/exception → Interceptor afterCompletion → Filter after chain.doFilter()
Why This Order Exists
Each component lives in a different stack. The closer to the underlying container, the earlier its logic is invoked; the closer to business code, the later it runs.
Filter: defined by the Java Servlet spec, runs before the request reaches Spring MVC.
Interceptor: native to Spring Web, runs inside DispatcherServlet before the controller method.
AOP: Spring’s dynamic‑proxy based enhancement, wraps the controller bean itself.
Full Request Flow (9 Stages)
Request enters Tomcat : TCP connection, HTTP parsed into HttpServletRequest, enters servlet chain.
All Filters pre‑handle : executed by priority order via doFilter and chain.doFilter() (e.g., charset, CORS, TraceId).
DispatcherServlet receives the request and performs handler mapping.
All Interceptors pre‑handle : preHandle() runs (e.g., login check, permission). Returning false aborts the chain.
Controller proxy AOP pre‑handle : around/before advice runs (parameter validation, timing start, transaction begin).
Controller method execution : business logic, service/DAO calls.
AOP after/return/exception advice : commit/rollback, timing end, result wrapping.
Interceptor afterCompletion : model‑view processing, resource cleanup.
Filter post‑handle : code after chain.doFilter() runs (response handling, context cleanup).
Component Capabilities and Boundaries
Filter – Servlet‑level Global Filter
Specification : Java Servlet standard, not Spring‑specific.
Target : every HTTP request entering the container.
Resources : HttpServletRequest, HttpServletResponse.
Core abilities : modify headers/body, block/allow requests, wrap request objects.
Typical scenarios : global CORS, character encoding, XSS/SQL injection filtering, TraceId injection, request‑body replay.
Limitation : cannot access Spring beans or controller method metadata.
Interceptor – Spring MVC Framework Interceptor
Specification : Spring Web module.
Target : requests that pass through DispatcherServlet (i.e., controller requests).
Resources : HttpServletRequest, HttpServletResponse, HandlerMethod (controller method metadata).
Core abilities : intercept controller execution, decide whether to proceed, insert logic before/after method.
Typical scenarios : login state validation, permission checks, request logging, rate limiting, user context injection.
Limitation : cannot intercept service/DAO methods; parameter binding not completed, so cannot directly obtain @RequestParam or @RequestBody values.
AOP – Bean‑level Dynamic Proxy Enhancement
Specification : Spring AOP module, based on JDK/CGLIB proxies.
Target : any Spring‑managed bean (controller, service, DAO).
Resources : method arguments, return value, exception object, method metadata.
Core abilities : around, before, after, and exception advice on any bean method.
Typical scenarios : declarative transactions ( @Transactional), method‑level performance monitoring, unified result wrapping, business operation logging, parameter validation.
Limitation : only works on public methods of Spring beans; internal method calls bypass the proxy; cannot directly manipulate request/response objects.
Sorting Rules Within the Same Component Type
When multiple implementations exist, the order value decides priority—smaller numbers mean higher priority (earlier pre‑handle, later post‑handle).
Filter Sorting
Annotation: @Order(1) on the filter class.
Registration bean: FilterRegistrationBean.setOrder(1).
Note: @WebFilter does not support @Order directly; combine with @Order or register via bean.
Interceptor Sorting
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// priority 1, executed first
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.order(1);
// priority 2, executed later
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/**")
.order(2);
}
}AOP Aspect Sorting
@Aspect
@Component
@Order(1)
public class LogAspect {
// high priority, runs before lower‑order aspects
}Exception Handling Flow
AOP exception advice ( @AfterThrowing) triggers first (e.g., transaction rollback).
Global exception handler ( @RestControllerAdvice) wraps the exception into a unified error response at the DispatcherServlet level.
Interceptor afterCompletion runs regardless of success or failure, suitable for resource cleanup and final logging.
Filter post‑handle runs last after the response has been written.
Common misconception: many think Filter catches the original exception first, but only the final wrapped response exception reaches Filter; the original exception is first seen by AOP.
When to Use Which Component
Global CORS configuration : use Filter (pre‑flight OPTIONS never reaches Interceptor).
TraceId injection : use Filter (applies to every request at the outermost layer).
Login/permission checks : use Interceptor (has access to controller metadata and can configure path patterns).
Declarative transactions : use AOP (operates on Service layer methods, independent of controller).
Method execution timing : use AOP (can wrap any bean method).
XSS filtering or request‑body rewriting : use Filter (modifies the raw request before Spring parses it).
Unified exception handling : place a @RestControllerAdvice between Interceptor and AOP.
Operation logging : can be done with Interceptor for controller‑level actions or AOP for service‑level actions.
Common Pitfalls and Solutions
CORS config in Interceptor does not work : OPTIONS request is intercepted by the servlet container. Solution: implement CORS with a Filter or Spring’s CorsFilter.
Interceptor cannot read @RequestParam/@RequestBody : parameters are not bound yet during preHandle. Solution: use AOP after parameter binding.
AOP aspect not effective : internal method calls, non‑public methods, or class not managed by Spring. Solution: ensure calls go through the Spring bean proxy and methods are public.
Request body can be read only once : reading in Filter consumes the stream. Solution: wrap the request with ContentCachingRequestWrapper to cache the body.
Exception swallowed by global handler prevents AOP @AfterThrowing : the method appears to return normally. Solution: place exception‑sensitive logic inside the global handler or advise the handler itself.
Conclusion
Filter, Interceptor, and AOP are not mutually exclusive choices but three cooperating layers—container → framework → bean. Understanding their execution order, sorting rules, and appropriate use cases prevents many hard‑to‑debug bugs and leads to clean, maintainable Spring Boot applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Workshop
Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
