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]
        }
    }
}

通過以上方法,即可找到你想要的參數注解,並拿到對應參數的值啦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM