DIGITAL GURU
Java DSA Portfolio

Spring Interceptors (HandlerInterceptor)

Learn Spring MVC HandlerInterceptor preHandle, postHandle, and afterCompletion lifecycle hooks.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Real-World Analogy

Think of a Spring Interceptor as a stage manager inside a theater—they check actors right before they step onto the stage (`preHandle`), inspect performance right after (`postHandle`), and clean the stage after the show finishes (`afterCompletion`).

HandlerInterceptor vs Servlet Filter

While Filters operate at the Servlet container level, Interceptors operate INSIDE the Spring MVC framework with full access to Spring beans and handler method metadata.

Lifecycle Hooks Explained:

  • preHandle(): Executes before Controller method invocation. Return false to block execution.
  • postHandle(): Executes after Controller method finishes, before view rendering.
  • afterCompletion(): Executes after request processing and rendering complete. Ideal for resource cleanup.

Production Code Example:

LoggingInterceptor.java
package com.anujsingh.digitalguru.interceptor;

import jakarta.servlet.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoggingInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        req.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }
}

Key Architectural Concepts & Best Practices:

When working with Spring Interceptors (HandlerInterceptor) in enterprise Spring Boot applications, keep these key architectural guidelines in mind:

  • Separation of Concerns: Maintain a strict boundary between HTTP endpoints, service logic, and database persistence layers.
  • Framework Conventions: Rely on Spring Boot auto-configuration defaults whenever possible, overriding settings only via application.yml or @Configuration classes when customized behavior is required.
  • Production Monitoring & Reliability: Ensure proper exception handling, thread-safety, and resource cleanup to prevent memory leaks and unexpected runtime downtime.
  • Developer Ergonomics: Write clean, self-documenting code with modern Java features (Records, Lambdas, Streams) to simplify code reviews and maintenance.

Summary Takeaway:

Mastering Spring Interceptors (HandlerInterceptor) ensures that your Java & Spring Boot backend microservices remain maintainable, secure, and compliant with modern enterprise software engineering standards.

Registration Requirement

Spring Interceptors must be explicitly registered inside a `@Configuration` class implementing `WebMvcConfigurer.addInterceptors()`.