我想在spring 4 webmvc应用程序中使用java配置。在Internet上浏览一些示例后,我有以下WebAppApplicationInitializer。将监听器添加到Spring中的servlet上下文中
public class AppInit implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "spring.examples.config";
private static final String MAPPING_URL = "/rest/*";
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(MAPPING_URL);
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
return context;
}
它工作正常,在码头,tomcat的,但是当我使用树脂4.0.40。 Web服务器会显示以下错误:
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml! at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:277) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at com.caucho.server.webapp.WebApp.fireContextInitializedEvent(WebApp.java:3777) at com.caucho.server.webapp.WebApp.startImpl(WebApp.java:3687) at com.caucho.server.webapp.WebApp.access$400(WebApp.java:207) at com.caucho.server.webapp.WebApp$StartupTask.run(WebApp.java:5234) at com.caucho.env.thread2.ResinThread2.runTasks(ResinThread2.java:173) at com.caucho.env.thread2.ResinThread2.run(ResinThread2.java:118)
当我注释此行
servletContext.addListener(new ContextLoaderListener(context));
一切工作正常。
问题是将监听器添加到servlet上下文的目的是什么?不向servlet上下文添加监听器是否错误?
为什么不通过web.xml定义侦听器,并让那容器处理它? – SMA 2014-11-03 15:47:17
我想要没有任何xml配置的web应用程序 – 2014-11-03 15:49:30
您可以用抛出它的类显示完整的错误信息吗? – 2014-11-03 16:08:20