如何在Spring AOP中的建议方法中从Custom Annotation获得值



我有这样的自定义注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CutomAnnotation{
String value() default "";
}

我的方面类如下:

@Aspect
@Component
public class MyCustomAspect{
@Around("@annotation(com.forceframework.web.handlers.monitoring.MeterRegTimer)")
public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("Timer started: "+joinPoint.getSignature());
Object objToReturn=joinPoint.proceed();
System.out.println("Timer ended: "+joinPoint.getSignature());
return objToReturn;
}
}

我在控制器类中使用注释的地方:

@CustomAnnotation(value="timer")
@GetMapping(value="/test")
public ResponseEntity test() {}

我想知道我是否可以访问从MyCustomAspect类中的绕过建议方法aroundJoinPoint中的CustomAnnotation传递的value

您的建议应声明如下:

@Around("@annotation(customAnnotationArgumentName)")
public Object aroundJoinPoint(ProceedingJoinPoint joinPoint, CustomAnnotation customAnnotationArgumentName) throws Throwable {
// ...
}

有关详细信息,请参阅文档。

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
CutomAnnotation methodAnnotation = method.getDeclaredAnnotation(CutomAnnotation.class);

最新更新