我正准备在雄猫上部署spring-mvc webapp WAR软件包。部署过程失败,并显示以下错误:“ java.lang.IllegalStateException:未设置ServletContext”
我猜我的配置有问题:(
我的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 {
}
就这样,只有两个bean。
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:未设置ServletContext
答案 0 :(得分:0)
我找到了解决方案:无需在applicationContext.refresh();
中调用org.springframework.web.WebApplicationInitializer#onStartup
,因为在将servlet装入servlet容器时,将在方法org.springframework.web.servlet.FrameworkServlet#configureAndRefreshWebApplicationContext
中自动调用它。
但是我使用spring.io文档中的示例:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet。他们为什么用这种方式? proof