在做一个跨过目标注解的鉴权功能时,想到了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.获取