Sign Up Spring HandlerInterceptor without WebMvcConfigurationSupport

I am trying to register an instance of HandlerInterceptor in Spring using Java Config without the WebMvcConfigurationSupport extension. I am creating a library with annotation that, when added to the @Configuration class @Configuration registers an interceptor that processes the security annotation.

I had an implementation using WebMvcConfigurationSupport#addInterceptors , but this was contrary to other automatic work in spring, and redefined part of the applicationโ€™s own logic. It also seems incredibly heavy for something that should be simple. I'm trying now:

 @Configuration public class AnnotationSecurityConfiguration { @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @PostConstruct public void attachInterceptors() { requestMappingHandlerMapping.setInterceptors(new Object[] { new SecurityAnnotationHandlerInterceptor() }); } } 

However, it seems that the interceptor is registering in a completely different instance of RequestMappingHandlerMapping than the one that the application actually uses for web requests. Also, when using BeanFactoryPostProcessor I get a NullPointerException in HealthMvcEndpoint when trying to beanFactory.getBean(RequestMappingHandlerMapping.class)

+7
source share
2 answers

Edit : This class has been deprecated since. See below @bosco for the Spring 5 equivalent.

It turned out that the solution should be used simply:

 @Configuration public class AnnotationSecurityConfiguration extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SecurityAnnotationHandlerInterceptor()); } } 

In the spring of loading, all beans like WebMvcConfigurer automatically detected and can change the MVC context.

+8
source

Just pointing out @Blauhirn's comment, WebMvcConfigurerAdapter deprecated since version 5.0 :

Deprecated version 5.0 WebMvcConfigurer has default methods (made possible by the Java 8 baseline) and can be implemented directly without using this adapter

Refer to the new way:

 @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyCustomInterceptor()) // Optional .addPathPatterns("/myendpoint"); } } 

Also, as stated here , do not comment on this with @EnableWebMvc if you want to keep the Spring Boot automatic configuration for MVC .

+3
source

Source: https://habr.com/ru/post/1211371/


All Articles