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
CodePudding user response:
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 Spring Boot (not plain Spring!) detects HandlerInterceptor
beans in the context and automatically registers them for you. This won't work in a regular Spring application.
So the way to use is to use the InterceptorRegistry
as that is the documented way and the MappedInterceptor
is more of an internal support class.