SpringBootTest失败,出现“ IllegalStateException-未设置ServletContext”

时间:2019-05-24 13:14:46

标签: spring spring-boot spring-boot-test shedlock

我有一个非常简单的@SpringBootTest

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {

    @Test
    public void anyTest() { ... }
}

它一直按预期运行,直到我们在@EnableSchedulerLock文件上添加了MyApplication.java(来自Shedlock)。

自此,我们遇到了这个问题:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
    ... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)

当Spring试图实例化其resourceHandlerMapping时会发生这种情况:

@Bean
public HandlerMapping resourceHandlerMapping() {
    Assert.state(this.applicationContext != null, "No ApplicationContext set");
    Assert.state(this.servletContext != null, "No ServletContext set");
    ...

这就像@Bean是在调用setServletContext(来自WebMvcConfigurationSupport)之前创建的。

1 个答案:

答案 0 :(得分:0)

如Lukas所述,此错误已在最新版本的Shedlock中修复。

将Shedlock的版本2.2.0升级到2.5.0即可解决此问题。