Mastering Spring Interceptors: How to Implement, Configure, and Optimize
Learn how Spring interceptors work, their relationship with WebApplicationContext, various types, configuration methods, execution flow, advanced features, and practical examples such as logging and authentication, plus a comparison with servlet filters and demo results.
Interceptor Overview
In the Spring framework, an Interceptor is a powerful mechanism that allows developers to insert custom logic at different stages of request processing. The WebApplicationContext provides the foundation for registering and managing interceptors.
Typical use cases include permission validation, logging, performance monitoring, transaction management, and generic behavior injection.
Relationship between Interceptor and WebApplicationContext
The WebApplicationContext is an extension of the Spring IoC container for web applications. Interceptors are registered and managed through the WebApplicationContext, becoming part of the request handling pipeline.
public interface WebApplicationContext extends ApplicationContext {
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
ServletContext getServletContext();
}Interceptor Types
HandlerInterceptor
The most common interceptor interface, defining three key methods:
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}AsyncHandlerInterceptor extends HandlerInterceptor to add asynchronous processing support.
WebRequestInterceptor
Similar to HandlerInterceptor but works with the more generic WebRequest abstraction and does not depend on the Servlet API.
Interceptor Configuration
Java configuration
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoggingInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static/**");
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/admin/**");
}
}Annotation-based configuration
@Component
public class MyInterceptor implements HandlerInterceptor {
// implement methods
}
@Configuration
public class InterceptorConfig {
@Autowired
private MyInterceptor myInterceptor;
@Bean
public WebMvcConfigurer adapter() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor);
}
};
}
}Interceptor Execution Flow
Interceptors play a key role in the DispatcherServlet processing pipeline:
preHandle : called before the handler execution; returning true continues processing, false aborts the request.
postHandle : called after the handler but before view rendering; can modify the ModelAndView.
afterCompletion : called after the complete request has finished; suitable for resource cleanup.
Advanced Interceptor Features
Interceptor Order Control
The order attribute can be used to control the execution sequence of multiple interceptors.
registry.addInterceptor(new InterceptorA()).order(1);
registry.addInterceptor(new InterceptorB()).order(2);Path Matching Patterns
Spring supports Ant-style path patterns:
Match a single character: ? Match zero or more characters: * Match zero or more directories:
**Asynchronous Request Handling
For asynchronous requests, afterConcurrentHandlingStarted is invoked instead of postHandle and afterCompletion.
Difference Between Interceptor and Filter
Interceptors are Spring MVC components managed by the Spring container, operate on requests handled by Spring MVC, can access handler and method information, execute inside the DispatcherServlet, and support dependency injection. Filters are servlet‑level components managed by the servlet container, apply to all incoming requests, only have access to the raw ServletRequest/Response, execute outside the DispatcherServlet, and do not support Spring injection.
Practical Application Examples
Logging Interceptor
public class LoggingInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
logger.info("Request URL: {} : Start Time={}", request.getRequestURL(), startTime);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
long startTime = (Long) request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
logger.info("Request URL: {} : End Time={} : Time Taken={}ms", request.getRequestURL(), endTime, (endTime - startTime));
}
}Authentication Interceptor
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("user") == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
}Demo Test Results
Intercepted request:
Not intercepted request:
JD Tech Talk
Official JD Tech public account delivering best practices and technology innovation.
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.
