草庐IT

java - Spring boot ComponentScan excludeFIlters 不排除

coder 2023-05-12 原文

我正在进行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 {
}

我正在尝试排除 Starter

package application.starters;

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

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

Application 类看起来像这样:

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 类?

最佳答案

每个组件扫描都会单独进行过滤。当您从 SimpleTestConfig 中排除 Starter.class 时,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
  • Starter 类上使用 Spring 配置文件和注解,例如 @Profile("!TEST")
  • Starter 类上使用 spring Boot @ConditionalOn... 注解

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

有关java - Spring boot ComponentScan excludeFIlters 不排除的更多相关文章

随机推荐