在做一个跨过目标注解的鉴权功能时,想到了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);
//....
//..业务逻辑代码
//..
}
}
最后
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
小编已加密:aHR0cHM6Ly9kb2NzLnFxLmNvbS9kb2MvRFVrVm9aSGxQZUVsTlkwUnc==出于安全原因,我们把网站通过base64编码了,大家可以通过base64解码把网址获取下来。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/114376.html