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. docker容器呢SSH为什么连不通呢?2. dockerfile - 为什么docker容器启动不了?3. golang - 用IDE看docker源码时的小问题4. docker api 开发的端口怎么获取?5. docker start -a dockername 老是卡住,什么情况?6. javascript - 表单ajax提交后跳转,手机按返回又进入这个表单页了!!7. javascript - 父级设置了相对定位。子元素设置了绝对定位。子元素中包含了浮动的table,这个时候高度不能自适应。8. Span标签9. javascript - vue异步数据打印问题10. javascript - js的string数据类型,这段表述是什么意思?
