繁体   English   中英

测试中未调用方法拦截器

[英]Method Interceptor not being called in Test

我的方法拦截器没有在测试上下文中调用。 测试上下文为我的测试 class: 配置了@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

当我用MyAnnotation调用方法时

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM