【问题标题】:DefaultAnnotationHandlerMapping via ContextLoaderListener instead of DispatcherServlet on Spring 3DefaultAnnotationHandlerMapping 通过 ContextLoaderListener 而不是 Spring 3 上的 DispatcherServlet
【发布时间】:2010-05-06 05:32:02
【问题描述】:

当我使用 DispatcherServlet 时,我得到一个 java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? 当我使用 DelegatingFilterProxy 过滤器时出现 错误。因此,我删除了 DispatcherServlet,现在我改用 ContextLoaderListener,我的 Spring 应用程序加载正常。但是,我对一个非常重要的 bean 有疑问:

   <context:component-scan base-package="com.mydomain"/>  
   <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
      <property name="interceptors">
         <list>
            <ref bean="openSessionInViewInterceptor" />
         </list>
      </property>
   </bean>

这个 bean 不再工作了,我的 @Controller 都不再是 URL 映射的了。如果我切换回使用 DispatcherServlet,没问题(除了我的过滤器又没用了)。如何让这个 bean 从 ContextLoaderListener 中正确加载?

干杯

尼克

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您需要ContextLoaderListener DispatcherServlet - 错误消息没有告诉您删除 servlet。

    为了阐明 Spring 在这里做什么,DispatcherServlet 创建了自己的 ApplicationContext(通常使用 xxx-servlet.xml),但是您在 web.xml 中配置的任何 Spring 过滤器都无法访问 servlet 的 @987654326 @。

    ContextLoaderListener 创建第二个 ApplicationContext(与整个 webapp 相关联),并将自身与 servlet 的 ApplicationContext 链接起来,从而允许过滤器和 servlet 通过 Spring 进行通信。

    【讨论】:

    • 啊哈!这很清楚。 :-) 但是,关于如何配置 ContextLoaderListener 以进入 Servlet 的上下文或其他方式,你有什么好的链接吗?因为当我同时使用这两种方法时,它会实例化每个 bean 两次(DefaultAnnotationHandler 除外,并且前提是我已将 context-param 的 contextConfigLocation 设置为 servlet 配置文件。如果我制作一个单独的配置文件,我需要复制/粘贴 bean用于身份验证,或导入数据和业务层,从而将所有这些 bean 制作两次。我怎样才能继续只拥有一次?
    • ContextLoaderListener创建的appcontext是servlet的appcontext的父上下文。这意味着 ContextLoaderListener 的 appcontext 中的 bean 对 servlet 的 appcontext 中的 bean 自动可见(但反之则不行)。所以任何共享的都应该在父级中声明。
    • 非常感谢,我不知道。我相应地修复了我的配置,现在一切正常。 :-) 非常感谢你,感谢你在这里帮助我的所有其他时间。我绝对需要找个时间给你买几瓶啤酒 :-)
    • 呜呜呜,你们都让我脸红了
    • 这不起作用,当我设置两个不同的上下文 xml,并在配置中设置 为 ContextConfigListener 设置的 xml,我只得到白页,但是当该定义在两个文件中时,它就可以工作。
    【解决方案2】:

    Spring MVC 基本应用的 web.xml 没有 ContextLoaderListener 吗?见https://src.springframework.org/svn/spring-samples/mvc-basic/trunk/src/main/webapp/WEB-INF/web.xml

    我问的原因是因为我的应用程序中出现以下错误:

    ERROR [[Spring MVC Dispatcher Servlet]] Servlet.service() for servlet Spring MVC Dispatcher Servlet 抛出异常 java.lang.IllegalStateException:未找到 WebApplicationContext:未注册 ContextLoaderListener?

    而且我没有 ContextLoaderListener(这可能会导致问题)。

    关于为什么 MVC 基本应用程序可以工作的任何想法?

    【讨论】:

    • 这个 mvc-basic 有效,因为它只使用过滤器 org.springframework.web.filter.CharacterEncodingFilter 并且这个过滤器不需要 Spring Application Context 来工作。
    猜你喜欢
    • 2016-09-12
    • 2012-06-14
    • 1970-01-01
    • 2013-05-18
    • 2014-03-01
    • 2013-08-25
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多