java - SpringAOP如何獲得執(zhí)行方法的class上的注解信息
問題描述
我想實(shí)現(xiàn)的功能是,如果在class上注解了需要驗(yàn)證用戶,那么里面的method就不需要逐個(gè)去寫這個(gè)注解。如果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. mysql優(yōu)化 - mysql count(id)查詢速度如何優(yōu)化?2. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應(yīng)用上有什么區(qū)別?3. angular.js - 不適用其他構(gòu)建工具,怎么搭建angular1項(xiàng)目4. 主從備份 - 跪求mysql 高可用主從方案5. css3 - [CSS] 動畫效果 3D翻轉(zhuǎn)bug6. node.js - node_moduls太多了7. angular.js - angularjs 用ng-reapt渲染的dom 怎么獲取上面的屬性8. python如何不改動文件的情況下修改文件的 修改日期9. python - django 里自定義的 login 方法,如何使用 login_required()10. android-studio - Android 動態(tài)壁紙LayoutParams問題
![css3 - [CSS] 動畫效果 3D翻轉(zhuǎn)bug](http://www.aoyou183.cn/attached/image/news/202304/110831f073.png)