我什么时候应该在 Spring 中使用 TypeExcludeFilters? [英] When should I use TypeExcludeFilters in Spring?
问题描述
最近,Spring Boot 增加了 TypeExcludeFilters.一个突出的用例是 SpringBootApplication 注释.
Recently, Spring Boot added TypeExcludeFilters. One prominent use case is the SpringBootApplication annotation.
在 Spring Boot 1.4 之前:
Before Spring Boot 1.4:
// ...
@ComponentScan
public @interface SpringBootApplication {
// ...
从 Spring Boot 1.4 开始:
Since Spring Boot 1.4:
// ...
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM,
classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// ...
主要动机似乎是改进 Spring 中的测试支持,但我无法直观地了解它的作用以及它在哪些情况下是有益的.
The main motivation seems to improve testing support in Spring, but I fail to get an intuitive understanding of what it does and in what situations it can be beneficial.
有人可以用一个简单的例子来说明这个新概念是如何使用的吗?
Can someone illustrate in a simple example how this new concept is intended to be used?
Background: The change came in Spring 1.4.0 with commit 513dec718fd3e7449ec76b6a916f4696d1942d5d:
添加一个新的 TypeFilter,专门用于排除候选组件.过滤器应用于 @SpringBootApplication
并允许测试动态贡献排除过滤器,以便特定类别的可以排除组件.
Add a new TypeFilter specifically for excluding candidate components. The filter is applied to
@SpringBootApplication
and allows tests to dynamically contribute exclude filters so that specific classes of component can be excluded.
推荐答案
一个有趣的例子是 @WebMvcTest
,因为它的工作归功于 TypeExcludeFilter
:
One interesting example is @WebMvcTest
, because it works thanks to a TypeExcludeFilter
:
//...
@TypeExcludeFilters(WebMvcTypeExcludeFilter.class)
//...
public @interface WebMvcTest {
...
}
WebMvcTypeExcludeFilter
最终实现了 TypeExcludeFilter
,用于确定是否不应为此测试加载组件/类.哪些不包括(排除)?好吧,WebMvcTypeExcludeFilter
默认包含一些类型:
WebMvcTypeExcludeFilter
ultimately implements TypeExcludeFilter
, which is used to determine if a component/class should not be loaded for this test. Which ones are not included (are excluded)? Well WebMvcTypeExcludeFilter
includes some types by default:
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 配置时被排除,有效地应用仅与 MVC 测试相关的配置",如 JavaDoc.
In essence, this WebMvcTypeExcludeFilter
will match any class that is not "included". By matching the filter, the class will be excluded when loading the spring configuration, effectively applying "only configuration relevant to MVC tests" as stated by the JavaDoc.
这篇关于我什么时候应该在 Spring 中使用 TypeExcludeFilters?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!