在我的旧 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 等而浪费时间?