Spring AOP 和 拦截器 获取类上与方法上的注解
在做一个获取目标注解的鉴权功能时,想到了AOP与拦截器两种方式,其中 @HasPermission 是我自定义的注解,
以下分别为AOP与拦截器获取访问目标类与方法上的注解的方法。由于我的系统在拦截器上配置了拦截过则,所以我选的是拦截器的方式,读者可根据自己的需求来。
一、Spring AOP方式获取方法上的注解
获取类上注解:
先通过ProceedingJoinPoint对象的 joinPoint.getSignature()方法获取到 Signature 的对象并强制类型转换为一个MethodSignature对象,通过 signature.getClass()方法获取到一个 Class 对象,最后通过 AnnotationUtils.findAnnotation()方法获取目标类上的目标注解;
获取方法上注解:
同理,通过 signature.getMethod()方法获取到一个 Method 对象,最后通过 AnnotationUtils.findAnnotation()方法获取目标方法上的目标注解。
@Aspect @Component public class PermissionAop { @Pointcut("execution(public * com.xxx.yyy.controller.*.*(..))") public void pointcut(){ } @Around("pointcut()") public ApiResult doAround(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //1.获取目标类上的目标注解(可判断目标类是否存在该注解) HasPermission annotationInClass = AnnotationUtils.findAnnotation(signature.getClass(), HasPermission.class); //2.获取目标方法上的目标注解(可判断目标方法是否存在该注解) HasPermission annotationInMethod = AnnotationUtils.findAnnotation(signature.getMethod(), HasPermission.class); //ps:如果1.无法获取类上的注解时 //使用反射的方式 /* * MethodSignature signature = (MethodSignature) joinPoint.getSignature(); * Class<?> tagClass = signatureInMethod.getDeclaringType(); * boolean annotation = tagClass.isAnnotationPresent(HasPermission.class); * HasPermission annotationInClass=null; * if(annotation){ * annotationInClass = tagClass.getAnnotation(HasPermission.class); * } * */ //.... //具体业务逻辑 //.... return (ApiResult) joinPoint.proceed(args); } }
二、拦截器方式获取方法上的注解
将 handler 强制转换为 HandlerMetho 对象,再通过 HandlerMethod 对象的handlerMethod.getBeanType() 方法获取到 Bean 对象,最后通过 AnnotationUtils.findAnnotation()方法获取目标类上的目标注解;
同理,通过handlerMethod.getMethod() 方法获取到 Method 对象,最后通过 AnnotationUtils.findAnnotation()方法获取目标方法上的目标注解。
@Component public class PermissionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { HandlerMethod handlerMethod = (HandlerMethod) handler; //1.获取目标类上的目标注解(可判断目标类是否存在该注解) HasPermission annotationInClass = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), HasPermission.class); //2.获取目标方法上的目标注解(可判断目标方法是否存在该注解) HasPermission annotationInMethod = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), HasPermission.class); //.... //..业务逻辑代码 //.. } }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_37778018/article/details/125326847

您的资助是我最大的动力!
金额随意,欢迎来赏!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2020-03-31 js代码中的parent,top和self有什么区别
2020-03-31 JS window对象的top、parent、opener含义介绍