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. angular.js - 百度支持_escaped_fragment_吗?2. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?3. node.js - Vue+Webpack在dev环境下没有问题build后出现莫名错误4. node.js - nodejs+express+vue5. css3 - 如图的flex骰子布局是怎么实现的?6. javascript - ios返回不执行js怎么解决?7. css3 - 这个CSS样式是什么意思?8. html - css布局问题,在firebug下<a>标签嵌入<img>标签但是高度<a>总比<img>多4个像素9. 微信公众号实现消息模板的推送?10. javascript - vue2.0中使用vue2-dropzone的demo,vue2-dropzone的github网址是什么??百度不到。
