【问题标题】:When should I use TypeExcludeFilters in Spring?我什么时候应该在 Spring 中使用 TypeExcludeFilters?
【发布时间】:2016-12-22 16:06:07
【问题描述】:

最近,Spring Boot 新增了TypeExcludeFilters。一个突出的用例是SpringBootApplication 注释。

在 Spring Boot 1.4 之前:

// ...
@ComponentScan
public @interface SpringBootApplication {
// ...

自 Spring Boot 1.4 起:

// ...
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, 
   classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// ...

主要动机似乎是改进 Spring 中的测试支持,但我无法直观地理解它的作用以及它在什么情况下可能是有益的。

有人可以用一个简单的例子来说明这个新概念是如何使用的吗?


背景:更改出现在 Spring 1.4.0 中,commit 513dec718fd3e7449ec76b6a916f4696d1942d5d:

添加一个新的 TypeFilter 专门用于排除候选组件。 过滤器应用于@SpringBootApplication 并允许测试 动态贡献排除过滤器,以便特定类别的 可以排除组件。

见gh-5295
见gh-4901

【问题讨论】:

  • 例如,如果您有许多来自第三方库的类,并且不需要对这些进行组件扫描。启动应用程序的改进不大。

标签: java spring spring-boot spring-test


【解决方案1】:

一个有趣的例子是@WebMvcTest,因为TypeExcludeFilter 可以工作:

//...
@TypeExcludeFilters(WebMvcTypeExcludeFilter.class)
//...
public @interface WebMvcTest {
    ...
}

WebMvcTypeExcludeFilter 最终实现了TypeExcludeFilter,用于确定是否不应该为此测试加载组件/类。哪些不包括(排除)?那么WebMvcTypeExcludeFilter默认包含一些类型:

static {
    Set<Class<?>> includes = new LinkedHashSet<>();
    includes.add(ControllerAdvice.class);
    includes.add(JsonComponent.class);
    includes.add(WebMvcConfigurer.class);
    ...
    DEFAULT_INCLUDES = Collections.unmodifiableSet(includes);
}

本质上,这个WebMvcTypeExcludeFilter 将匹配任何未被“包含”的类。通过匹配过滤器,加载 spring 配置时将排除该类,有效地应用 JavaDoc 中所述的“仅与 MVC 测试相关的配置”。

【讨论】:

    【解决方案2】:

    说出于某种原因(例如在集成测试中)您不希望某些 bean(甚至标有 @Component 或 @Service)在应用程序上下文中注册。

    这可以通过实现TypeExcludeFilter 并将其应用于测试类来实现:

    @SpringBootTest
    @TypeExcludeFilters(YourTypeExcludeFilter.class)
    public class YouIntegrationTest() {
    

    有关如何实现TypeExcludeFilter 的示例,请查看TestTypeExcludeFilter。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2018-06-26
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多