【发布时间】:2019-10-03 08:53:45
【问题描述】:
我正在尝试在 tomcat 上部署 spring-mvc webapp WAR-package。部署过程失败并出现以下错误:'java.lang.IllegalStateException: No ServletContext set'
我猜我的配置有问题:(
- Tomcat 版本:8.5.46
- Spring、spring-mvc 版本:5.1.9.RELEASE
- 来自 spring.io 的示例配置代码:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet
我的 webapp 初始化器:
package com.jbtits.spring.mvc.webac;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(AppConfig.class);
applicationContext.refresh();
DispatcherServlet servlet = new DispatcherServlet(applicationContext);
ServletRegistration.Dynamic registration = servletContext.addServlet("webac", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
我的 webapp 配置:
package com.jbtits.spring.mvc.webac;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
@EnableWebMvc
@ComponentScan("com.jbtits.spring.mvc.webac")
public class AppConfig extends WebMvcConfigurationSupport {
}
就是这样,只有两个豆子。
Tomcat 失败输出:
2019 年 10 月 2 日 18:02:52.971 警告 [http-nio-8081-exec-84] org.springframework.context.support.AbstractApplicationContext.refresh 上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework。 beans.factory.BeanCreationException:创建 org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration 中定义的名称为“resourceHandlerMapping”的 bean 时出错:通过工厂方法进行 Bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.web.servlet.HandlerMapping]:工厂方法“resourceHandlerMapping”抛出异常;嵌套异常是 java.lang.IllegalStateException: No ServletContext set
【问题讨论】:
-
不要扩展
WebMvcConfigurationSupport,要么实现WebMvcConfigurere,或者如果在旧版本上扩展WebMvcConfigurerAdapter。 -
尝试扩展 AbstractAnnotationConfigDispatcherServletInitializer 并覆盖“getServletMappings”、“getRootConfigClasses”和“getServletConfigClasses”,而不是 WebApplicationInitializer。
-
相同的行为,导致
org.springframework.web.context.support.ServletContextAwareProcessor无法设置ServletContext(此时它不存在)。这个PostProcessor用于两种变体 -
太难了,不是吗?
标签: java spring spring-mvc