When to Use Filter, Interceptor, or AOP in Spring Boot? A Practical Guide
This article explains the concepts, execution order, and ideal use‑cases of Spring Boot's Filter, Interceptor, and AOP, compares their characteristics, and provides a selection guide and best‑practice recommendations for building maintainable backend applications.
1. Basic Concepts and Execution Order
1. Filter
Filter is defined by the Servlet specification, runs in the web container before the request reaches the servlet and after the response leaves the client.
@Component
public class LogFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
log.info("请求URL: {}", req.getRequestURI());
// continue the filter chain
chain.doFilter(request, response);
log.info("响应已完成");
}
}2. Interceptor
Interceptor is provided by Spring MVC, placed after the DispatcherServlet and before the controller.
@Component
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
// called before controller method execution
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
// called after controller method but before view rendering
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
// called after the whole request is completed
}
}3. AOP
AOP is a programming paradigm provided by Spring that can add functionality to methods without modifying the source code.
@Aspect
@Component
public class PerformanceAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
log.info("{} 执行耗时 {} ms", joinPoint.getSignature(), executionTime);
return result;
}
}Execution Order
The processing order is: Filter → Interceptor → AOP → Controller → AOP → Interceptor → Filter
2. Comparison of Usage Scenarios
Filter operates on all HTTP requests at the servlet level, cannot obtain method or class information, and is suitable for request/response preprocessing such as character encoding, CORS handling, logging, and sensitive‑information filtering.
Interceptor works on matched URL requests within Spring MVC, can access method information, and is ideal for authentication, authorization, performance monitoring, detailed logging, and internationalization.
AOP works on specified methods inside the Spring container, can access method parameters and return values, and is used for transaction management, performance monitoring, logging, caching, and unified exception handling.
3. Selection Guide
When to Choose Filter
Need to process every HTTP request.
Need preprocessing before the request reaches the controller.
Functionality related to the Servlet specification.
Need to modify request or response objects.
Implement framework‑agnostic features.
When to Choose Interceptor
Need to use Spring MVC specific features.
Need access to the controller context.
Only intercept matching URL requests.
Require flexible request‑intercept configuration.
Need multiple handling stages (pre‑handle, post‑handle, after‑completion).
When to Choose AOP
Need to intercept specific method execution.
Need to handle cross‑cutting concerns in the business layer.
Need access to method parameters and return values.
Require finer‑grained control.
Enhance non‑Web layer functionality.
4. Best Practices
Combine Usage
In real projects these three techniques are often combined: use Filter for generic web request handling (e.g., encoding, CORS), Interceptor for authentication/authorization, and AOP for business‑layer cross‑cutting concerns such as logging, performance monitoring, and transactions.
Performance Considerations
Filter and Interceptor are applied once per request.
AOP may affect multiple methods and increase call points.
In high‑concurrency scenarios, minimize the number and complexity of AOP advices.
Code Organization
Place authentication and authorization logic in Interceptor.
Use AOP for logging, monitoring, and other generic concerns.
Use Filter for request preprocessing such as character encoding.
5. Summary
Choosing the right technique depends on specific requirements, performance considerations, and team familiarity. Combining them appropriately leads to modular, maintainable applications. For Spring Boot, follow the principle of separation of concerns and select the implementation that matches the nature of the cross‑cutting concern.
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 Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
