【问题标题】:Adding listener to servlet context in Spring在 Spring 中将侦听器添加到 servlet 上下文
【发布时间】:2014-12-30 07:28:04
【问题描述】:

我正在尝试在 spring 4 webmvc 应用程序中使用 java config。在网上浏览了一些示例后,我有了以下 WebAppApplicationInitializer。

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 时。网络服务器显示以下错误:

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 定义监听器,让容器处理呢?
  • 我想要一个没有任何 xml 配置的 web 应用程序
  • 你能用抛出它的类显示完整的错误消息吗?
  • Serge,我在堆栈跟踪中添加了错误

标签: java spring servlets resin


【解决方案1】:

问题是树脂 4.0.40 中的错误 http://bugs.caucho.com/view.php?id=5611ServletContextListener#contextInitialized() 打了两次电话。在树脂 4.0.41 中一切正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 2014-09-03
    • 1970-01-01
    • 2013-02-17
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多