You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 01:09:18