我正在使用 SimpleTest :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SimpleTestConfig.class)
public class SimpleTest {
    @Test
    public void test() {
        assertThat(true);
    }
}

以及此测试的配置:
@SpringBootApplication
@ComponentScan(basePackageClasses = {
        SimpleTestConfig.class,
        Application.class
},
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.ASSIGNABLE_TYPE,
                classes = Starter.class))
public class SimpleTestConfig {
}

我正在尝试排除入门
package application.starters;

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class Starter {
    @PostConstruct
    public void init(){
        System.out.println("initializing");
    }
}

应用程序类如下所示:
package application;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import static org.springframework.boot.SpringApplication.run;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        run(Application.class, args);
    }
}

但是出于一个非常奇怪的原因, Starter 类仍在初始化。

谁能解释为什么ComponentScan excludeFilters不排除我的Starter类?

最佳答案

每个组件扫描都单独进行过滤。当您从Starter.class中排除SimpleTestConfig时,SimpleTestConfig会初始化Application,这是它自己的@ComponentScan,但不排除Starter
使用ComponentScan的简单方法是让每个ComponentScan扫描单独的程序包,这样每个筛选器都可以正常工作。当2个单独的ComponentScans扫描相同的程序包时(如您的测试中一样),这将不起作用。

解决这个问题的一种方法是提供一个模拟的Starter bean:

import org.springframework.boot.test.mock.mockito.MockBean;

public class SimpleTest {
    @MockBean
    private Starter myTestBean;
    ...
}

Spring将使用该模拟代替实际的类,因此不会调用@PostConstruct方法。

其他常见解决方案:
  • 不要在任何单元测试
  • 中直接使用Application.class
  • @Profile("!TEST")
  • 上使用Spring配置文件和批注,例如Starter
  • @ConditionalOn...
  • 上使用spring boot Starter批注

    关于java - Spring Boot ComponentScan excludeFIlters不排除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48102883/

    10-10 17:58