在Spring Java Config文件中创建Aspect bean会导致另一个bean无法自动装配

时间:2015-04-06 15:00:56

标签: junit mockito spring-aop spring-java-config

尝试测试Spring AOP类时有一个奇怪的问题。

这是类似的设置,因为我无法将实际代码放在这里。

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@ContextConfiguration(classes = {MyTestConfiguration.class})
public class MyTest {

    @Autowired
    private MyService1 myService1;

    @Autowired
    private MyService2 myService2;


    @Test
    public void testAop() {
        myService1.methodToBeIntercepted();
        verify(myService2).create();
    }
}

Spring Java配置文件:

@EnableAspectJAutoProxy
@Configuration
public class MyTestConfiguration {
    @Bean
    public MyService1 myService1() {
        return new MyService1Impl();
    }

    @Bean
    public MyService2 myService2() {
        return Mockito.mock(MyService2.class);
    }
}

AOP课程:

@Aspect
@Component
public class MyAop {
    @Autowired
    private MyService2 myService2;

    @Around("execution(* package.MyService1.methodToBeIntercepted(..))")
    public void interception(ProceedingJoinPoint joinPoint) {

       // do stuff

       MyReturn myReturn = (MyReturn) joinPoint.proceed();

       myService2.create();
    }
}

通过这个设置,我得到一个错误,说测试想要执行myService2.create(),但没有。这意味着AOP类没有正确拦截调用,并且Spring配置是正确的,因为找到了所有的bean。

接下来,我将以下内容添加到MyTestConfiguration中,为AOP类创建bean:

@Bean
public MyAop myAop() {
    return new MyAop();
}

现在我收到Spring错误,说它无法找到MyService1 bean,因此测试永远不会运行。现在简单地将myAop bean添加到MyTestConfiguration会导致Spring不再识别MyService1 bean。

我做错了什么,如果是的话,是什么?

0 个答案:

没有答案