测试中未调用方法拦截器

时间:2021-05-18 10:54:03

标签: java spring aop spring-aop

我的方法拦截器未在测试上下文中调用。为我的测试类配置了测试上下文:使用 @ContextConfiguration(locations = {"classpath:testContext.xml"}) 并且我有一个方法拦截器:

public class MyMethodInterceptor implements MethodInterceptor {

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

它在我的 context.xml 文件中配置如下:

<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>

当我用 MyAnnotation 调用一个方法时,我的期望是在我的测试中,拦截器正在被调用,但它不会。我正在使用 JUnit 4.12

1 个答案:

答案 0 :(得分:1)

<块引用>

当我用 MyAnnotation 调用方法时

无论是在测试还是在生产代码中,这都行不通。原因很简单:方法拦截器和 @within() 切入点指示符的使用截然相反:

@within() 拦截带注释的类内的所有内容(即在Spring AOP方法执行中),而根据您的描述,您要拦截带注释的方法。 >

解决方案是使用 @annotation(path.to.annotation.MyAnnotation) 并注释所有目标方法,或者继续使用 @within(path.to.annotation.MyAnnotation),但改为注释目标类。