Adding HTTP Request Interceptors in Spring Boot for Logging

Nov 21, 2025 · Programming · 10 views · 7.8

Keywords: Spring Boot | HTTP Interceptor | Logging | WebMvcConfigurer | HandlerInterceptor

Abstract: This article provides a comprehensive guide on implementing HTTP request interceptors in Spring Boot applications to log request and response details. Based on the latest Spring Boot versions, it explains core concepts such as HandlerInterceptor and WebMvcConfigurer, offers step-by-step implementation instructions with code examples, and discusses best practices like avoiding deprecated adapters and maintaining auto-configuration.

Introduction

In web application development, intercepting HTTP requests and responses is a common requirement for tasks such as logging, authentication, or performance monitoring. Spring Boot, as a popular Java framework, offers flexible mechanisms to achieve this. This article, based on community Q&A and best practices, guides readers on how to add HTTP request interceptors in Spring Boot, with a focus on logging scenarios. By leveraging Spring's auto-configuration and modern interfaces, we can easily extend application functionality without disrupting existing structures.

Core Concepts

HTTP request interceptors in Spring MVC are implemented through the HandlerInterceptor interface, which defines three key methods: preHandle executes before request processing, postHandle after request processing but before view rendering, and afterCompletion after request completion. In Spring Boot, we use the WebMvcConfigurer interface to register these interceptors, avoiding the deprecated WebMvcConfigurerAdapter. This ensures forward compatibility and utilizes Java 8's default method features.

Implementation Steps

To add an HTTP request interceptor, first create a custom interceptor class that implements the HandlerInterceptor interface and overrides the relevant methods. Then, define a configuration class that implements the WebMvcConfigurer interface and registers the interceptor in the addInterceptors method. It is crucial not to use the @EnableWebMvc annotation to preserve Spring Boot's auto-configuration. This way, the interceptor can be applied to all or specific path patterns of requests.

Code Examples

Here is a complete example demonstrating how to implement a logging interceptor. First, define the interceptor class:

public class LoggingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Pre-handle: Request URI - " + request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Post-handle: Response Status - " + response.getStatus());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("After completion: Request completed");
    }
}

Next, define the configuration class to register the interceptor:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor()).addPathPatterns("/**");
    }
}

In this example, the interceptor is applied to all paths ("/**"), and you can adjust the path patterns as needed. The code uses System.out.println for simple logging output; in real-world applications, it is recommended to integrate logging frameworks like SLF4J.

Best Practices

When implementing interceptors, prefer dependency injection over direct instantiation to enhance testability and loose coupling. For instance, inject the interceptor instance using @Autowired. Additionally, avoid the @EnableWebMvc annotation as it overrides Spring Boot's default MVC configuration. Referencing community discussions, use the WebMvcConfigurer interface instead of deprecated adapters to ensure compatibility with the latest Spring versions. Interceptor logic should remain lightweight to avoid blocking operations and maintain application performance.

Conclusion

Through this guide, readers can successfully add HTTP request interceptors in Spring Boot applications to achieve efficient logging functionality. This approach leverages Spring's auto-configuration and modern APIs, ensuring code simplicity and maintainability. Future enhancements could include extending interceptor capabilities, such as adding more complex log formats or integrating monitoring tools, to further improve application observability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.