Home  >  Q&A  >  body text

java - How does SpringAOP obtain the annotation information on the class that executes the method?

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;
            }
        }
    }
天蓬老师天蓬老师2667 days ago930

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-06-30 09:56:55

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

    reply
    0
  • 怪我咯

    怪我咯2017-06-30 09:56:55

    You can read this article Java annotations

    reply
    0
  • typecho

    typecho2017-06-30 09:56:55

    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 "" ;   

    }

    reply
    0
  • Cancelreply