如何通过Spring AOP获取带@CustomAnnotation方法中@CustomValue参数的值
解决方案
要获取标注了@CustomAnnotation的方法中带@CustomValue注解的参数值,可以通过JoinPoint获取方法签名与实际参数,结合参数注解信息匹配对应值,具体实现如下:
具体代码实现
@AfterReturning(value = "@annotation(customAnnotation)", argNames = "jp, customAnnotation") public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) { // 1. 获取方法签名与目标方法 MethodSignature methodSignature = (MethodSignature) jp.getSignature(); Method targetMethod = methodSignature.getMethod(); // 2. 获取方法的参数注解(二维数组:每个参数对应一组注解) Annotation[][] parameterAnnotations = targetMethod.getParameterAnnotations(); // 3. 获取方法调用时的实际参数值 Object[] args = jp.getArgs(); // 4. 遍历参数注解,匹配@CustomValue并取出对应参数值 for (int i = 0; i < parameterAnnotations.length; i++) { Annotation[] annotations = parameterAnnotations[i]; for (Annotation annotation : annotations) { if (annotation instanceof CustomValue) { Object annotatedParamValue = args[i]; // 此处可对获取到的参数值进行后续业务处理 System.out.println("带@CustomValue的参数值:" + annotatedParamValue); } } } }
关键说明
MethodSignature是JoinPoint签名的子类,专门用于获取方法相关信息,通过它能拿到目标方法的Method对象。getParameterAnnotations()返回二维数组,外层数组对应方法的每个参数,内层数组对应该参数上的所有注解。- 遍历注解数组时,判断是否为
@CustomValue实例,匹配成功后直接从args数组中通过索引取出对应参数值。 - 若方法中没有标注
@CustomValue的参数,循环会自然跳过,不会产生异常,适配参数数量为0的场景。
内容的提问来源于stack exchange,提问作者user688291
相关产品推荐
相关产品推荐

