javaspringspring-bootspring-mvc

MappedInterceptor Bean Vs WebMvcConfigurer addInterceptors. What is the correct (modern) way for adding Spring HandlerInterceptor?


I stumbled upon a configuration class for a project that was converted from legacy spring to Spring Boot. I see there are two ways interceptors are added. Like these

  @Configuration
  public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");
    }

    @Bean
    public MappedInterceptor mappedResponseHeaderInterceptor() {
        return new MappedInterceptor(new String[] { "/static/css/**", "/static/img/**" }, new ResponseHeaderInterceptor());
    }
  }
  

both interceptors are working. I am wondering what is right way to add the interceptors in Spring boot and why these two method exists


Solution

  • Basically they are the same.

    registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");
    

    Will internally use the MappedInterceptor to register the HandlerInterceptor with the given URL pattern.

    Now the registration of a HandlerInterceptor (which MappedInterceptor implements) as an @Bean works because the AbstractHandlerMapping (base class for all HandlerMapping implementations), will detect those when it is being constructed (added in Spring 3.1).