I have an HandlerInterceptor that I want to only apply to requests that map to a particular Controller. I can add the interceptor in a WebMvcConfigurer as follows:
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final MyInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(interceptor).addPathPatterns("/path", "/path/**");
}
}
But this requires me to keep the configuration class in line with the Controller by hand. I would like to be able to do this by just saying 'only apply this interceptor to this controller'.
Is this possible in Spring Boot 2.7.
Note: iff the Controller class has a class-level @RequestMapping annotation, this is a slightly more programmatic way of obtaining the path patterns, but not quite the 'all paths to the controller' solution I'd really like.
InterceptorRegistration interceptorRegistration = registry.addInterceptor(interceptor);
RequestMapping annotation = controllerClass.getAnnotation(RequestMapping.class);
for (String rootPath : annotation.value()) {
interceptorRegistration.addPathPatterns(rootPath, rootPath + "/**");
}