review interceptors

Table of Contents

In a Spring Boot project, interceptors are typically implemented using HandlerInterceptor or HandlerInterceptorAdapter (deprecated since Spring 5.3). These interceptors allow you to intercept HTTP requests before they reach the controller.

1. Checking How Many Interceptors Are Registered

To see all the interceptors in your Spring Boot application, you can do the following:

Approach 1: Print Registered Interceptors in WebMvcConfigurer

If interceptors are registered via WebMvcConfigurer, you can list them by overriding addInterceptors method:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired(required = false) // To avoid issues if no interceptors are present
    private List<HandlerInterceptor> interceptors;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (interceptors != null) {
            System.out.println("Registered Interceptors:");
            for (HandlerInterceptor interceptor : interceptors) {
                System.out.println(interceptor.getClass().getName());
            }
        }
    }
}

Approach 2: Debugging with Breakpoints

You can set breakpoints inside:

  • WebMvcConfigurer#addInterceptors
  • HandlerInterceptor#preHandle
  • HandlerInterceptor#postHandle
  • HandlerInterceptor#afterCompletion

Then, run your application and inspect the interceptor chain when requests are processed.


2. Checking Where and How an Interceptor Works

Once you identify the interceptors, you can analyze how they work by looking at their implementations. Here’s how interceptors typically work:

A Sample Custom Interceptor

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("Before handler execution: " + request.getRequestURI());
        return true; // Continue request processing
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           org.springframework.web.servlet.ModelAndView modelAndView) {
        System.out.println("After handler execution: " + request.getRequestURI());
    }

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

Registering the Interceptor

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoggingInterceptor loggingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggingInterceptor).addPathPatterns("/**");
    }
}

3. Dynamically Inspecting Interceptors

If you want to check interceptors at runtime, you can use:

import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class InterceptorInspector {

    private final WebApplicationContext context;

    public InterceptorInspector(WebApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    public void printInterceptors() throws Exception {
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
        Map<String, HandlerMapping> handlerMappings = context.getBeansOfType(HandlerMapping.class);

        for (Map.Entry<String, HandlerMapping> entry : handlerMappings.entrySet()) {
            HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
            if (chain != null) {
                System.out.println("Interceptors for " + entry.getKey() + ":");
                for (var interceptor : chain.getInterceptors()) {
                    System.out.println(interceptor.getClass().getName());
                }
            }
        }
    }
}

This will list all interceptors applied to different routes in your Spring Boot application.


4. Using Spring Boot Actuator (For Monitoring)

If you have spring-boot-starter-actuator dependency, you can inspect handler mappings (including interceptors):

  1. Add dependency

    
       org.springframework.boot
       spring-boot-starter-actuator
    
  2. Enable Actuator Endpoint in application.properties

    management.endpoints.web.exposure.include=*
  3. Check Mappings via HTTP Request

    GET http://localhost:8080/actuator/mappings

    This will return all handler mappings, including the interceptors.


Summary

Approach How it helps?
Logging in addInterceptors Prints interceptors when they are registered.
Breakpoints in Interceptor methods Debugs execution flow.
Runtime Inspection (HandlerExecutionChain) Lists interceptors for specific routes.
Spring Boot Actuator (/actuator/mappings) Provides all request mappings and interceptors.

Would you like more details on any specific aspect? 🚀

Comments |0|

Legend *) Required fields are marked
**) You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Category: 似水流年