Search code examples
javaspringspring-aop

Get annotated param value from annotated method using Spring AOP


I have a program written in Java 11 with two custom annotation. One on Method level and one on Parameter level. I`m using Spring AOP to act on methods that use my Custom annotations. 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. @CustomValue is useless if the method is not annotated with @CustomAnnotation. And the number of parameters that can be annotated with @CustomValue is 0 or more.

How can I get the values from the parameters that is annotated with @CustomValue on a method that is annotated with @CustomAnnotation?


Solution

  • 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];
            }
        }
    }