@ComponentScan in application class breaks @WebMvcTest and @SpringBootTest

元气小坏坏 提交于 2019-12-22 13:50:14

问题


I am creating tests with @WebMvcTest annotation and found that if I have a @ComponentScan annotation in the application class it will break the expected behavior of the tests.

According to the WebMvcTest javadoc:

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans)."

The problem is that with @ComponentScan it is instantiating beans annotated with @Service. If instead of @ComponentScan I specify the scan base packages in the @SpringBootApplication annotation everything works as expected.

Another problem happens when I specify the controller class in the @WebMvcTest annotation. When there is a @ComponentScan annotation in the application class it will load all controllers instead of loading only the specified one.

Is this a bug in Spring Boot?

I want to use @ComponentScan because of the excludeFilters attribute which is not available in the @SpringBootApplication annotation.

A workaround I have found is to create a separate class with @Configuration annotation and move the @ComponentScan there.


回答1:


Found the reason for this odd behavior.

This is the declaration of the @SpringBootApplication annotation:

@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 {

As you can see the @ComponentScan annotation inside the @SpringBootApplication has the excludedFilters attribute specified.

When I added the @ComponentScan annotation directly in my application class I did not specify the default excludedFilters and that is why the behavior was different.



来源:https://stackoverflow.com/questions/47054716/componentscan-in-application-class-breaks-webmvctest-and-springboottest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!