AOP方法拦截获取参数上的注解

https://www.jianshu.com/p/f5c7417a75f9

获取参数注解

在spring aop中,无论是前置通知的参数JoinPoint,还是环绕通知的参数ProceedingJoinPoint,都可以通过以下方法获得入参:
MethodSignature signature= (MethodSignature) jp.getSignature();

 
根据源码分析,MethodSignature封装了两个方法,一个获取方法的返回值类型,一个是获取封装的Method对象,

getReturnType()可以用在环绕通知中,我们可以根据这个class类型,做定制化操作.而method的参数和参数上的注解,就可以从getMethod()返回的Method对象中拿,api如下:
// 获取方法上的注解
XXX xxx = signature.getMethod().getAnnotation(XXX.class)
//获取所有参数上的注解
Annotation[][] parameterAnnotations= signature.getMethod().getParameterAnnotations();

只有所有的参数注解怎么获取对应参数的值呢?

获取所有参数注解返回的是一个二维数组Annotation[][],每个参数上可能有多个注解,是一个一维数组,多个参数又是一维数组,就组成了二维数组,所有我们在遍历的时候,第一次遍历拿到的数组下标就是方法参数的下标,
for (Annotation[] parameterAnnotation: parameterAnnotations) {
    int paramIndex= ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
}
再根据Object[] args= joinPoint.getArgs();拿到所有的参数,根据指定的下标即可拿到对象的值
for (Annotation[] parameterAnnotation: parameterAnnotations) {
    int paramIndex= ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
    for (Annotation annotation: parameterAnnotation) {
        if (annotation instanceof XXX){
                Object paramValue = args[paramIndex]
        }
    }
}

通过以上方法,即可找到你想要的参数注解,并拿到对应参数的值啦!

原文地址:https://www.cnblogs.com/kelelipeng/p/12009680.html