从测试上下文中排除类

Mih*_* L. 5 spring spring-boot

如何在一个需要扫描所有包的<import>另一个上下文中从组件扫描中加载一些bean xml.如果我把它放到主要的上下文中,这很有效:

<context:component-scan base-package="com.main">
        <context:exclude-filter expression="com.main.*Controller" type="regex"/>
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)

但我需要在现场环境中使用控制器.

我想从集成测试上下文中排除控制器类加载.怎么可能实现这个目标?

Ale*_*can 5

您可以为此使用spring配置文件(请参阅如何将Spring配置文件设置为包?

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
        <!-- define profile beans at the end of the configuration file -->
    <beans profile="test">
    <context:component-scan base-package="com.main">
            <context:exclude-filter expression="com.main.*Controller" type="regex"/>
    </context:component-scan>
    </beans>

    <beans profile="!test">
    <context:component-scan base-package="com.main"/>
    </beans>
Run Code Online (Sandbox Code Playgroud)

并用特定的注释来注释您的测试 @ActiveProfile("test")

编辑:

如果您的xml没有定义<component:scan>标签,则可以使用Java配置从单元测试中控制程序包扫描。然后可以使用@ComponentScanexcludeFilter 排除控制器,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class HelperTest {

    @Configuration
    @ComponentScan(basePackages = "yourPackage",
            excludeFilters = @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION))
    @ImportResource(locations = "classpath:context.xml")
    static class TestConfiguration {


    }
Run Code Online (Sandbox Code Playgroud)