java - How does SpringAOP obtain the annotation information on the class that executes the method?
天蓬老师
天蓬老师 2017-06-30 09:54:55
0
3
986

The function I want to achieve is that if there is an annotation on class that requires user verification, then the method inside does not need to write this annotation one by one.
If method has written annotations, the method shall prevail.

After checking, I found that most articles talk about how to obtain the annotations on method, but not how to obtain the annotations on class.
Please God give me a piece of code.

Combined with the adopted answer, the complete code is as follows:

private AuthType getAuthType(ProceedingJoinPoint pj) {
        // 获取切入的 Method
        MethodSignature 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;
            }
        }
    }
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
Ty80

Use Spring’s own toolsorg.springframework.core.annotation.AnnotationUtils#findAnnotation(java.lang.Class<?>, java.lang.Class<A>)

刘奇

You can read this article Java annotations

typecho

aop cut here

@Around("log() && @annotation(XXX.XXX.XXX.ControllerApiAnnotationLogin)")

Customized annotations

/**
*@author whmyit@163.com
*@Time 2017-06-16

  • Custom annotation control API
    */

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface ControllerApiAnnotationLogin {

  String name()  default "" ;   

}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template