selvinsource
selvinsource

Reputation: 1837

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?

Upvotes: 12

Views: 17675

Answers (1)

Sunil Pidugu
Sunil Pidugu

Reputation: 235

You can access spring controller class level annotations in the interceptor using handler method. But you have to be aware that the Casting to HandlerMethod might throw an exception because no Method was found (404)

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  System.out.println("Pre-handle");
  HandlerMethod hm;
  try {
   hm = (HandlerMethod) handler;
  } catch (ClassCastException e) {
   return super.preHandle(request, response, handler);
  }
  Method method = hm.getMethod();
  // Sometimes Controller.class wont work and you have to use RestController.class just depends on what you use.
  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;
 }

Upvotes: 19

Related Questions