【问题标题】:Spring HandlerInterceptor: how to access class annotations?Spring HandlerInterceptor:如何访问类注解?
【发布时间】:2015-03-31 10:36:58
【问题描述】:

我使用以下代码注册了我的拦截器

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

这里是拦截器定义

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

但是 handler.getClass().getDeclaredAnnotations() 没有返回被截获的控制器的类级别注释。

在这种情况下,我只能获得方法级别的注释,这不是我想要的。

同样的拦截器适用于 xml 配置(使用 Spring 3):

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

有没有办法在 Spring 4 中获取类级别信息?

根据 In a Spring-mvc interceptor, how can I access to the handler controller method? 使用上面的配置,“HandlerInterceptors 只会让你访问 HandlerMethod”。但是获取类级别信息的替代配置是什么?

【问题讨论】:

  • 你在比较苹果和橘子。 DefaultAnnotationHandlerMapping 是旧版本并且已弃用的较新版本(包括 java 配置)使用 RequestMethodHandlerMapping 在 XML 中使用它会导致相同的结果(如果您想将苹果与苹果进行比较)。如前所述,您将获得HandlerMethod 类型的对象,使用该类的getBean 方法来获取执行您请求的实际对象。或者使用getMethod获取选中的方法。
  • @selvinsource 你确定handler 对象是你认为的类型吗?它可能是一个代理对象,因此getDeclaredAnnotations 可能无法处理它。
  • 感谢您的输入,我找到了解决方案:((HandlerMethod)handler).getBean().getClass().getDeclaredAnnotations())

标签: java spring spring-mvc


【解决方案1】:

您可以使用处理程序方法访问拦截器中的spring控制器类级别注释。 但是你必须知道,转换为 HandlerMethod 可能会抛出异常,因为没有找到方法(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;
 }

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2015-03-16
    • 2016-11-24
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多