Search code examples
javaspringaopspring-aop

Method Interceptor not being called in Test


My method interceptor isn't called in test context. the test context is configured for my test class: with @ContextConfiguration(locations = {"classpath:testContext.xml"}) and I have a method interceptor:

public class MyMethodInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    System.out.println("invocation >>>> " + invocation);
}

and it's configured in my context.xml file like this:

<bean id="myMethodInterceptor" class="path.to.interceptor.MyMethodInterceptor"/>

<aop:config>
    <aop:advisor pointcut="@within(path.to.annotation.MyAnnotation)"
                 advice-ref="myMethodInterceptor" order="10"/>
</aop:config>

my expectation is in my test when I call a method with MyAnnotation the interceptor is being called, but it will not. I'm using JUnit 4.12


Solution

  • when I call a method with MyAnnotation

    This will never work, neither in a test nor in production code. The reason is simple: A method interceptor and use of the @within() pointcut designator are diametrically opposed to each other:

    @within() intercepts everything (i.e. in Spring AOP method executions) inside annotated classes, while according to your description you want to intercept annotated methods.

    The solution would be to either use @annotation(path.to.annotation.MyAnnotation) and annotate all target methods, or to continue using @within(path.to.annotation.MyAnnotation), but annotate target classes instead.