我什么时候应该在 Spring 中使用 TypeExcludeFilters?

Phi*_*ßen 7 java spring spring-test spring-boot

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

Spring Boot 1.4 之前:

// ...
@ComponentScan
public @interface SpringBootApplication {
// ...
Run Code Online (Sandbox Code Playgroud)

从 Spring Boot 1.4 开始:

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

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

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


背景:更改发生在 Spring 1.4.0 中,提交为 513dec718fd3e7449ec76b6a916f4696d1942d5d

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

参见gh-5295
参见gh-4901

Nat*_*Far 4

一个有趣的例子是@WebMvcTest,因为它的工作原理是TypeExcludeFilter

//...
@TypeExcludeFilters(WebMvcTypeExcludeFilter.class)
//...
public @interface WebMvcTest {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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