2

I have a method annotation (@MethodAnno) and a parameter annotation (@P). I need to create an aspect to capture invocations of methods annotated with @MethodAnno and look up method arguments annotated with @P. However while I am able to obtain the method annotation in my aspect, parameter annotations are not returned in MethodSignature. Below is what I have.

Annotations

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MethodAnno {

    Foo[] foo();

}

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface P {

    Bar value();
}

Aspect

@Aspect
@Component
public class MyAspect {

    @Before("@annotation(methodAnnotation)")
    public void methodsWithMethodLevelAnnotation(final JoinPoint pjp, MethodAnno methodAnnotation) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();

        // parameterAnnotations is always a single element array and the element is a zero-length array
    }
}

Usage

public interface Service {
    public void execute(String input);
}

@Service    
public class ServiceImpl implements Service {
    @Override
    @MethodAnno
    public void execute(@P String input) {
        ....
    }
}
citress
  • 889
  • 3
  • 13
  • 35
  • One error that I can see is that your pointcut expression checks for `"@annotation(methodAnnotation)"`, whereas the actual annotation you have defined is called `MethodAnno`. – filpa May 24 '18 at 20:07
  • Using @annotation(methodAnnotation) in my pointcut, where 'methodAnnotation' is the name of the pointcut method parameter name, allows me to get an instance of my method annotation MethodAnno. – citress May 24 '18 at 20:20
  • Oops, you're correct - my apologies for misreading. Since your class is implementing an interface, you will need to get the *actual* method that is being called. See [this](https://stackoverflow.com/a/6631829/991710) answer. – filpa May 24 '18 at 20:33
  • Thank you!! If you add your comment as the answer I will accept it. – citress May 25 '18 at 13:26
  • That's OK - glad I could help. You should just upvote the other answer I linked to instead. :) – filpa May 25 '18 at 21:31

0 Answers0