栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring AOP 和 拦截器 获取类上与方法上的注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
        
        //....
        //具体业务逻辑
        //....
        
        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);

    	//....
    	//..业务逻辑代码
    	//..
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977816.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号