Spring HandlerInterceptor: how to access class annotations?

I registered my interceptor with the following code

@EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { ... @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor( myInterceptor() ); } ... } 

Here is the definition of an interceptor

 public class MyInterceptorimplements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Check to see if the handling controller is annotated for (Annotation annotation : Arrays.asList(handler.getClass().getDeclaredAnnotations())){ if (annotation instanceof MyAnnotation){ ... do something 

However, handler.getClass (). getDeclaredAnnotations () does not return Controller interceptor class level annotations.

I can only get method level annotations that I don't want in this case.

The same interceptor works fine with xml configuration (using Spring 3):

 <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="myInterceptor"/> </list> </property> </bean> 

Is there a way to get class level information in Spring 4?

According to Spring -mvc interceptor, how can I access the controller controller method? "HandlerInterceptors will give you access to HandlerMethod" using the configuration above. But what is the alternative configuration for getting class level information?

+8
source share
1 answer

You can access the annotator class level annotation in the interceptor using a handler method.

 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("Pre-handle"); HandlerMethod hm = (HandlerMethod)handler; Method method = hm.getMethod(); if(method.getDeclaringClass().isAnnotationPresent(Controller.class)) { if(method.isAnnotationPresent(ApplicationAudit.class)) { System.out.println(method.getAnnotation(ApplicationAudit.class).value()); request.setAttribute("STARTTIME",System.currentTimemillis()); } } return true; } 
+6
source

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


All Articles