[英]Get annotated param value from annotated method using Spring AOP
I have a program written in Java 11 with two custom annotation.我有一个用 Java 11 编写的程序,带有两个自定义注释。 One on Method level and one on Parameter level.
一个在方法级别,一个在参数级别。 I`m using Spring AOP to act on methods that use my Custom annotations.
我正在使用 Spring AOP 对使用我的自定义注释的方法进行操作。 But I have not found a way to get the value ouf of an optional annotation that is on Parameter level.
但是我还没有找到一种方法来获取参数级别的可选注释的值。
@CustomAnnotation
public void myMethod(@CustomValue String param1, int param2) {
...
}
@AfterReturning(value = "@annotation(customAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
...
}
The program works well with my @CustomAnnotation, but I have problems to get the value out of parameters that is annotated with @CustomValue.该程序适用于我的@CustomAnnotation,但我无法从使用@CustomValue 注释的参数中获取值。 @CustomValue is useless if the method is not annotated with @CustomAnnotation.
如果方法没有使用@CustomAnnotation 注释,@CustomValue 将毫无用处。 And the number of parameters that can be annotated with @CustomValue is 0 or more.
并且可以使用@CustomValue 注释的参数数量为0 个或更多。
How can I get the values from the parameters that is annotated with @CustomValue on a method that is annotated with @CustomAnnotation?在使用@CustomAnnotation 注释的方法上,如何从使用@CustomValue 注释的参数中获取值?
@AfterReturning(value = "@annotation(CustomAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
CustomAnnotation annotation = customAnnotation;
List<Parameter> parameterList = new ArrayList<>();
if (jp.getSignature() instanceof MethodSignature) {
MethodSignature signature =
(MethodSignature) jp.getSignature();
Method method = signature.getMethod();
anno = method.getAnnotation(CustomAnnotation.class);
Parameter[] params = method.getParameters();
for (Parameter param : params) {
try {
if(param.getAnnotation(CustomValue.class) !=null){
parameterList.add(param);
}
} catch (Exception e) {
//do nothing
}
}
}
}
You should now get the list of parameters annotated with @CustomValue.您现在应该获得带有@CustomValue 注释的参数列表。 This exact code may not work while copy-paste, but you should get the idea.
这个确切的代码在复制粘贴时可能不起作用,但你应该明白。
Maybe there is a better way, but I solved this by using following:也许有更好的方法,但我通过使用以下方法解决了这个问题:
@AfterReturning(value = "@annotation(customAnnotation)", argNames = "customAnnotation, jp")
public void afterReturning(JoinPoint jp, CustomAnnotation customAnnotation) {
MethodSignature signature = (MethodSignature) jp.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
Object[] args = jp.getArgs();
for (int i = 0; i < args.length; ++i) {
if (parameters[i].isAnnotationPresent(CustomValue.class)) {
Object paramValue = args[i];
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.