java - SpringAOP如何获得执行方法的class上的注解信息

查看:238
本文介绍了java - SpringAOP如何获得执行方法的class上的注解信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想实现的功能是,如果在class上注解了需要验证用户,那么里面的method就不需要逐个去写这个注解。
如果method写了注解,则以method的为准。

查了一下,发现多数文章说的都是如何获得method上的注解,而没有说到如何获得class上的注解。
求大神赐予我一段代码。

结合采纳的答案,完整代码如下:

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

解决方案

用Spring自带工具org.springframework.core.annotation.AnnotationUtils#findAnnotation(java.lang.Class<?>, java.lang.Class<A>)

这篇关于java - SpringAOP如何获得执行方法的class上的注解信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆