应用程序类中的@ComponentScan 中断@WebMvcTest 和@SpringBootTest

Con*_*ger 7 spring-boot spring-boot-test

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

根据WebMvcTestjavadoc:

使用此批注将全面禁用自动配置,而是只适用于相关的测试MVC(即配置@Controller@ControllerAdvice@JsonComponent FilterWebMvcConfigurerHandlerMethodArgumentResolver咖啡豆,但没有@Component@Service@Repository豆类)“。

问题是@ComponentScan它正在实例化用@Service. 如果不是@ComponentScan我在@SpringBootApplication注释中指定扫描基础包,一切都按预期工作。

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

这是 Spring Boot 中的错误吗?

我想使用@ComponentScan是因为注释中excludeFilters没有的属性@SpringBootApplication

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

Con*_*ger 9

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

这是@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 {
Run Code Online (Sandbox Code Playgroud)

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

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