java - SpringAOP如何獲得執行方法的class上的注解信息
問題描述
我想實現的功能是,如果在class上注解了需要驗證用戶,那么里面的method就不需要逐個去寫這個注解。如果method寫了注解,則以method的為準。
查了一下,發現多數文章說的都是如何獲得method上的注解,而沒有說到如何獲得class上的注解。求大神賜予我一段代碼。
結合采納的答案,完整代碼如下:
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 '' ;
}
相關文章:
1. javascript - 在靜態頁面上用load 引入的頁面文件問題?2. java后臺導出頁面到pdf3. javascript - webpack打包后的bundlejs文件代碼不知道什么意思.4. Java游戲服務器開發和網站、app服務端的開發都差不多的嗎???實現的思路和方法5. android - RxJavar用什么操作符可以使數據每隔一段時間取出一個6. html - 哪些情況下float會失效?7. css - 關于ul的布局8. css - 如何使用 vue transition 實現 ios 按鈕一樣的平滑切換效果9. java - oracle對漢字字段按照拼音排序的函數和sql語句是什么?10. javascript - vue組件通過eventBus通信時,報錯a.$on is not a function
