如何从ProceedingJoinPoint获取方法的注释值?

如何从ProceedingJoinPoint获取方法的注释值?,第1张

如何从ProceedingJoinPoint获取方法注释值?

您可以从ProceedingJoinPoint获取签名,如果方法调用,只需将其转换为MethodSignature即可。

@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")public Object procede(ProceedingJoinPoint call) throws Throwable {    MethodSignature signature = (MethodSignature) call.getSignature();    Method method = signature.getMethod();    MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);}

但是,您应该首先添加一个注释属性。您的示例代码没有一个,例如

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    String value();}

然后就可以访问它

MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);String value = myAnnotation.value();

编辑

如果我在班级有@MyAnnotation(“ ABC”),如何获取价值?

A

Class
也是A
AnnotatedElement
,因此您可以从A
获得相同的方式
Method
。例如,可以使用以下方法获取方法声明类的注释:

 Method method = ...; Class<?> declaringClass = method.getDeclaringClass(); MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class)

由于您正在使用spring,因此您可能还需要使用spring的

AnnotationUtils.findAnnotation(..)
。它像spring一样搜索注释。例如,还要查看超类和接口方法等。

 MyAnnotation foundAnnotation = AnnotationUtils.findAnnotation(method, MyAnnotation.class);

编辑

您可能还会

MergedAnnotations
对5.2中引入的spring的功能感兴趣。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5506183.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存