【问题标题】:@ComponentScan in application class breaks @WebMvcTest and @SpringBootTest应用程序类中的 @ComponentScan 会破坏 @WebMvcTest 和 @SpringBootTest
【发布时间】:2018-04-13 18:17:39
【问题描述】:

我正在使用@WebMvcTest 注释创建测试,发现如果我在应用程序类中有@ComponentScan 注释,它将破坏测试的预期行为。

根据WebMvcTestjavadoc:

使用此注解将禁用完全自动配置,而是仅应用与 MVC 测试相关的配置(即 @Controller@ControllerAdvice@JsonComponent FilterWebMvcConfigurerHandlerMethodArgumentResolver bean,但不是 @Component、@ 987654330@ 或 @Repository 豆子)。”

问题是@ComponentScan 是实例化带有@Service 注释的bean。如果我在 @SpringBootApplication 注释中指定扫描基础包而不是 @ComponentScan,则一切都按预期工作。

当我在@WebMvcTest 注释中指定控制器类时,会发生另一个问题。当应用程序类中有@ComponentScan 注解时,它将加载所有控制器,而不是仅加载指定的控制器。

这是 Spring Boot 中的错误吗?

我想使用@ComponentScan,因为excludeFilters 属性在@SpringBootApplication 注释中不可用。

我发现的一种解决方法是使用@Configuration 注释创建一个单独的类并将@ComponentScan 移动到那里。

【问题讨论】:

    标签: spring-boot spring-boot-test


    【解决方案1】:

    找到了这种奇怪行为的原因。

    这是@SpringBootApplication注解的声明:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(excludeFilters = {
            @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
            @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    public @interface SpringBootApplication {
    

    如您所见,@SpringBootApplication 中的@ComponentScan 注解指定了excludedFilters 属性。

    当我直接在我的应用程序类中添加 @ComponentScan 注释时,我没有指定默认的 excludeFilters,这就是行为不同的原因。

    【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2021-07-28
    相关资源
    最近更新 更多