java - SpringAOP如何取得執行方法的class上的註解訊息
天蓬老师
天蓬老师 2017-06-30 09:54:55
0
3
937

我想實現的功能是,如果在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;
            }
        }
    }
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(3)
Ty80

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

刘奇

可以看看這篇文章 Java註解

typecho

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 "" ;   

}

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!