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

如何在Spring AOP的通知方法中获取自定义注解的属性值?

可以获取自定义注解的value属性值

首先需要修正几个拼写错误:

  • 自定义注解类名你写成了CutomAnnotation,但控制器里用的是@CustomAnnotation,统一改成CustomAnnotation避免编译错误
  • 切面类中@Around的注解路径写错了,应该指向你自己的CustomAnnotation,而非MeterRegTimer

下面提供两种可行的获取方式:

方式一:通过@annotation直接绑定注解参数

修改切面的环绕通知方法,在切点表达式中绑定注解实例,直接在方法参数中接收,就能轻松获取value值:

@Aspect
@Component
public class MyCustomAspect{

    // 绑定CustomAnnotation到方法参数
    @Around("@annotation(customAnnotation)")
    public Object aroundJoinPoint(ProceedingJoinPoint joinPoint, CustomAnnotation customAnnotation) throws Throwable{
        // 直接获取注解的value属性
        String annotationValue = customAnnotation.value();
        System.out.println("Timer started: "+joinPoint.getSignature() + " | 注解value: " + annotationValue);
        
        Object objToReturn=joinPoint.proceed();
        
        System.out.println("Timer ended: "+joinPoint.getSignature() + " | 注解value: " + annotationValue);
        return objToReturn;
    }
}

方式二:通过JoinPoint获取方法上的注解

如果不想修改切点绑定参数,可以通过ProceedingJoinPoint拿到目标方法,再获取注解实例:

@Aspect
@Component
public class MyCustomAspect{

    @Around("@annotation(com.yourpackage.CustomAnnotation)") // 替换成你实际的包路径
    public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable{
        // 获取目标方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        
        // 获取方法上的CustomAnnotation注解
        CustomAnnotation customAnnotation = method.getAnnotation(CustomAnnotation.class);
        if(customAnnotation != null){
            String annotationValue = customAnnotation.value();
            System.out.println("Timer started: "+joinPoint.getSignature() + " | 注解value: " + annotationValue);
        }
        
        Object objToReturn=joinPoint.proceed();
        
        if(customAnnotation != null){
            System.out.println("Timer ended: "+joinPoint.getSignature() + " | 注解value: " + annotationValue);
        }
        return objToReturn;
    }
}

注意:确保自定义注解的@Retention是RUNTIME,这样才能在运行时通过反射获取到注解信息,你当前的注解定义已经满足这个要求。

内容的提问来源于stack exchange,提问作者Kalindu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:01:23