首頁  >  問答  >  主體

java - SpringAOP如何取得執行方法的class上的註解訊息

我想實現的功能是,如果在class上註解了需要驗證用戶,那麼裡面的method就不需要逐一去寫這個註解。
如果method寫了註解,則以method的為準。

查了一下,發現多數文章說的都是如何獲得method上的註解,而沒有說到如何獲得class上的註解。
求大神賜給我一段程式碼。

結合採納的答案,完整程式碼如下:

private AuthType getAuthType(ProceedingJoinPoint pj) {
        // 获取切入的 Method
        MethodSignature joinPointObject = (MethodSignature) pj.getSignature();
        Method method = joinPointObject.getMethod();

        boolean flag = method.isAnnotationPresent(AuthTarget.class);
        if (flag) {
            AuthTarget annotation = method.getAnnotation(AuthTarget.class);
            return annotation.value();
        } else {
            // 如果方法上没有注解,则搜索类上是否有注解
            AuthTarget classAnnotation = AnnotationUtils.findAnnotation(joinPointObject.getMethod().getDeclaringClass(), AuthTarget.class);
            if (classAnnotation != null) {
                return classAnnotation.value();
            } else {
                return null;
            }
        }
    }
天蓬老师天蓬老师2667 天前931

全部回覆(3)我來回復

  • PHP中文网

    PHP中文网2017-06-30 09:56:55

    用Spring自備工具org.springframework.core.annotation.AnnotationUtils#findAnnotation(java.lang.Class, java.lang.Class)

    回覆
    0
  • 怪我咯

    怪我咯2017-06-30 09:56:55

    可以看看這篇文章 Java註解

    回覆
    0
  • typecho

    typecho2017-06-30 09:56:55

    aop中切這裡

    @Around("log() && @annotation(XXX.XXX.XXX.ControllerApiAnnotationLogin)")

    自訂註解

    /**
    *@author whmyit@163.com
    *@Time 2017-06-16

    • 自訂註解 控制 API
      */

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD,ElementType.TYPE})
    public @interface ControllerApiAnnotationLogin {

      String name()  default "" ;   

    }

    回覆
    0
  • 取消回覆