且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

@WebMvcTest 因 java.lang.IllegalStateException 失败:无法加载 ApplicationContext

更新时间:2022-11-26 10:22:52

我找到了我遇到这个问题的原因.来自 spring 文档 @SpringBootApplication:

I found the reason I was having this problem. From spring docs @SpringBootApplication:

表示声明一个或多个@Bean方法并触发自动配置和组件扫描的配置类.这是一个方便的注解,相当于声明了@Configuration、@EnableAutoConfiguration 和@ComponentScan.

Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.

然而,这是@SpringBootApplication注解的完整声明:

However, this is the full declaration of the @SpringBootApplication annotation:

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

当我直接在我的应用程序类中添加 @ComponentScan 注释时,我没有指定默认的 excludeFilters,这就是行为不同的原因.添加 excludeFilter 后,我能够解决我的问题.

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. After adding the excludeFilter I was able to solve my issue.