java - SpringAOP如何獲得執(zhí)行方法的class上的注解信息
問題描述
我想實現(xiàn)的功能是,如果在class上注解了需要驗證用戶,那么里面的method就不需要逐個去寫這個注解。如果method寫了注解,則以method的為準(zhǔn)。
查了一下,發(fā)現(xiàn)多數(shù)文章說的都是如何獲得method上的注解,而沒有說到如何獲得class上的注解。求大神賜予我一段代碼。
結(jié)合采納的答案,完整代碼如下:
private AuthType getAuthType(ProceedingJoinPoint pj) {// 獲取切入的 MethodMethodSignature 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; }} }
問題解答
回答1:用Spring自帶工具org.springframework.core.annotation.AnnotationUtils#findAnnotation(java.lang.Class<?>, java.lang.Class<A>)
回答2:可以看看這篇文章 Java注解
回答3: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 '' ;
}
相關(guān)文章:
1. php - mysql 模糊搜索問題2. 請問連接文件怎么寫3. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?4. php - 微信開發(fā)驗證服務(wù)器有效性5. python沒入門,請教一個問題6. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發(fā)現(xiàn)7. [python2]local variable referenced before assignment問題8. javascript - 我的站點貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?9. javascript - js setTimeout在雙重for循環(huán)中如何使用?10. javascript - 求幫助 , ATOM不顯示界面!!!!
