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 the interceptor definition

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 the handler.getClass().getDeclaredAnnotations() is not returning the class level annotations of the Controller intercepted.

I can only get the method level annotations which is not what I 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 have class level information in Spring 4?

According to In a Spring-mvc interceptor, how can I access to the handler controller method? "HandlerInterceptors will only provide you access to the HandlerMethod" using the configuration above. But what is the alternative configuration to get class level information?


you can access spring controller class level annotation in interceptor using 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; 
} 

check this example for more info http://www.myjavarecipes.com/spring-profilingaudit-using-mvc-interceptors/

链接地址: http://www.djcxy.com/p/84384.html

上一篇: 在Apache Spark中。 如何设置worker / executor的环境变量?

下一篇: Spring HandlerInterceptor:如何访问类注解?