如何在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
相关产品推荐
相关产品推荐

