1

在我的旧 XML 配置项目中,我可以在我的配置中执行以下操作

mvc-context.xml

<context:component-scan base-package="com.foo" use-default-filters="false">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

<mvc:annotation-driven/>

service-context.xml

<context:spring-configured />
<context:annotation-config />

<context:component-scan base-package="com.foo" >
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>

在我的测试中,我可以执行以下操作

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy(value = {
    @ContextConfiguration(classes = { MockServices.class }),
    @ContextConfiguration({ "classpath:/META-INF/spring/mvc-servlet-context.xml" }),
})
public class FooControllerTest {
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = webAppContextSetup(wac).build();
    }
}

然后我可以针对我的 MVC 配置运行测试,而无需加载我的服务和 JPA 存储库,而是将我的模拟@Autowired放入我的控制器中。

但是,Spring Boot 应用程序在主上下文配置中具有以下内容

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
}

@ComponentScan显然找到了 all @Controller,@Service

如果我现在尝试测试我的 MVC 上下文,我会加载不需要的服务和存储库。

我试图做的是创建 2 个新配置

Mvc.java

@Configuration
@ComponentScan(basePackages = { "com.foo" }, useDefaultFilters = false, includeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} )
@Order(2)
public class Mvc {
}

Services.java

@Configuration
@ComponentScan(basePackages = { "com.foo" }, useDefaultFilters = false, excludeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} )
@Order(1)
public class Services {
}

但是这不起作用,当我尝试启动我的应用程序时,我会收到@Autowire错误No qualifying bean of type

我会以错误的方式解决这个问题吗?

如何做到这一点,以便我可以在我的 MVC 上下文上运行测试,而不会因加载 JPA EntityManagers、Spring Data Repositories 等而浪费时间?

4

1 回答 1

0

M. Deinum在评论中给出的解决方案是正确的,但可能是您没有得到提示。当你说: useDefaultFilters = false并且excludeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} 什么都找不到,因为这useDefaultFilters = false会阻止spring寻找刻板印象注释,比如@Controller, @Service ...

链接到 Spring API 文档

于 2014-10-24T09:31:37.560 回答