獲取參數(shù)注解
在spring aop中,無論是前置通知的參數(shù)JoinPoint,還是環(huán)繞通知的參數(shù)ProceedingJoinPoint,都可以通過以下方法獲得入?yún)?
MethodSignature signature= (MethodSignature) jp.getSignature();
getReturnType()可以用在環(huán)繞通知中,我們可以根據(jù)這個(gè)class類型,做定制化操作.而method的參數(shù)和參數(shù)上的注解,就可以從getMethod()返回的Method對(duì)象中拿,api如下:
// 獲取方法上的注解
XXX xxx = signature.getMethod().getAnnotation(XXX.class)
//獲取所有參數(shù)上的注解
Annotation[][] parameterAnnotations= signature.getMethod().getParameterAnnotations();
只有所有的參數(shù)注解怎么獲取對(duì)應(yīng)參數(shù)的值呢?
獲取所有參數(shù)注解返回的是一個(gè)二維數(shù)組Annotation[][],每個(gè)參數(shù)上可能有多個(gè)注解,是一個(gè)一維數(shù)組,多個(gè)參數(shù)又是一維數(shù)組,就組成了二維數(shù)組,所有我們?cè)诒闅v的時(shí)候,第一次遍歷拿到的數(shù)組下標(biāo)就是方法參數(shù)的下標(biāo),
for (Annotation[] parameterAnnotation: parameterAnnotations) {
? ? int paramIndex= ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
}
再根據(jù)Object[] args= joinPoint.getArgs();拿到所有的參數(shù),根據(jù)指定的下標(biāo)即可拿到對(duì)象的值
for (Annotation[] parameterAnnotation: parameterAnnotations) {
? ? int paramIndex= ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
? ? for (Annotation annotation: parameterAnnotation) {
? ? ? ? if (annotation instanceof XXX){
? ? ? ? ? ? ? ? Object paramValue = args[paramIndex]
? ? ? ? }
? ? }
}
通過以上方法,即可找到你想要的參數(shù)注解,并拿到對(duì)應(yīng)參數(shù)的值啦!