繁体   English   中英

Spring boot ComponentScan excludeFIlters 不排除

[英]Spring boot ComponentScan excludeFIlters not excluding

我有一个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 ,它在不排除Starter情况下执行自己的@ComponentScan 使用 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...注释

您可以定义自定义组件扫描过滤器以排除它。

示例代码如下:

@SpringBootApplication()
@ComponentScan(excludeFilters=@Filter(type = FilterType.REGEX, pattern="com.wyn.applications.starter.Starter*"))
public class SimpleTestConfig {

}

这对我有用。

如需进一步阅读,请访问此博客

@SpringBootApplication ,根据Spring文档,它的组合功能包括: @ Configuration@ EnableAutoConfiguration@ComponentScan

首先尝试不改进包扫描(不使用basePackages过滤器)。

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM