Java 春天我应该什么时候使用TypeExcludeFilters?
最近,SpringBoot增加了一个新功能。一个突出的用例是注释 在Spring Boot 1.4之前:Java 春天我应该什么时候使用TypeExcludeFilters?,java,spring,spring-boot,spring-test,Java,Spring,Spring Boot,Spring Test,最近,SpringBoot增加了一个新功能。一个突出的用例是注释 在Spring Boot 1.4之前: // ... @ComponentScan public @interface SpringBootApplication { // ... // ... @ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class)) public @inte
// ...
@ComponentScan
public @interface SpringBootApplication {
// ...
// ...
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM,
classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// ...
从Spring Boot 1.4开始:
// ...
@ComponentScan
public @interface SpringBootApplication {
// ...
// ...
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM,
classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// ...
主要动机似乎是改善Spring中的测试支持,但我无法直观地理解它的作用以及在什么情况下它是有益的
有人能用一个简单的例子来说明这个新概念是如何使用的吗
背景:在Spring 1.4.0中进行了以下更改: 添加一个新的TypeFilter,专门用于排除候选组件。 过滤器应用于
@springbootplication
,并允许测试
动态贡献排除过滤器,以便
可以排除组件
见看
一个有趣的例子是
@WebMvcTest
,因为它是通过TypeExcludeFilter
工作的:
//...
@TypeExcludeFilters(WebMvcTypeExcludeFilter.class)
//...
public @interface WebMvcTest {
...
}
WebMvcTypeExcludeFilter
最终实现了TypeExcludeFilter
,用于确定是否不应为此测试加载组件/类。哪些不包括(不包括在内)?WellWebMvcTypeExcludeFilter
默认包括一些类型:
static {
Set<Class<?>> includes = new LinkedHashSet<>();
includes.add(ControllerAdvice.class);
includes.add(JsonComponent.class);
includes.add(WebMvcConfigurer.class);
...
DEFAULT_INCLUDES = Collections.unmodifiableSet(includes);
}
静态{
设置假设由于某种原因(例如在集成测试中),您不希望在应用程序上下文中注册某些bean(甚至标有@Component
或@Service
)
这可以通过实现TypeExcludeFilter
并将其应用于测试类来实现:
@SpringBootTest
@TypeExcludeFilters(YourTypeExcludeFilter.class)
public class YouIntegrationTest() {
有关如何实现TypeExcludeFilter
的示例,请查看。例如,如果您有许多来自第三方库的类,并且不需要对这些类进行组件扫描。启动应用程序的改进很少。