【问题标题】:Why DispatcherServlet creates another application context?为什么 DispatcherServlet 创建另一个应用程序上下文?
【发布时间】:2011-12-11 15:17:00
【问题描述】:

我已经使用ContextLoaderListener 和上下文初始化参数contextConfigLocation 配置了根应用程序上下文。

然后由 JSF (*.jsf) 变量解析器访问根上下文。它工作正常。

现在的问题是,通过 DispatcherServlet 的请求 (*.do) 将获得另一个应用程序上下文,然后单例 bean 被实例化两次。

我不需要DispatcherServlet 的另一个应用程序上下文,如何指定它以重用由ContextLoaderListener 加载的现有根应用程序上下文?

注意

阅读答案中的参考页面后,我知道根上下文和调度程序上下文之间存在上下文分离,但没有任何参考告诉我该去哪里。所以这是我的解决方案,可能对面临类似问题的其他人有所帮助:

  1. 在调度程序 servlet 的上下文配置 XML 中:dispatcher-servlet.xml,我复制了已在根上下文中定义的 <context:component-scan/>。所以删除它。 dispatcher-servlet.xml 只需要定义那些仅用于 Spring MVC 的 bean。

  2. 所有的控制器都已经在根上下文中被扫描和实例化,但是,Spring MVC 默认情况下不会在根上下文中注册控制器以进行请求映射。您可以:

    2.1。在根上下文中,从<component-scan> 中排除@Controller,并仅在dispatcher-servlet.xml 中扫描@Controller

    2.2。或者,将属性 DefaultAnnotationHandlerMapping.detectHandlersInAncestorContexts 设置为 true:

    (dispatcher-servlet.xml:)
    
    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="detectHandlersInAncestorContexts" value="true" />
    </bean>
    

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

如果你有一个DispatcherServlet 正在运行,则不需要使用ContextLoaderListener。只需使用ContextLoader.getCurrentWebApplicationContext() 访问WebApplicationContext

只需将 bean 定义分开as outlined in this previous answer

【讨论】:

  • 但是如果不使用ContextLoaderListener,就没有根上下文,ContextLoader.getCurrentWebApplicationContext()会返回null。
【解决方案2】:

为了回答您的第一个问题,DispatcherServlet 创建了一个上下文,因为这是它允许自己配置的方式,如果您在一个应用程序中有多个 DispatcherServlet,则需要分别配置它们。因此,每个上下文都有自己的上下文,并且每个上下文都与“根”上下文分开,所有真正的“工作”bean 都应该存在于其中,以便它们可以在其他上下文之间共享。在过去的几周里,由于对这个问题的困惑而产生了许多问题。通过查看答案,您可能会更好地了解事情的运作方式:

Spring XML file configuration hierarchy help/explanation

Declaring Spring Bean in Parent Context vs Child Context

Spring-MVC: What are a "context" and "namespace"?

【讨论】:

  • 那么如果你的调度器上下文中有一个控制器,它如何从根上下文中注入 bean?我不断收到 NoSuchBeanDefinitionExceptions
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2012-02-08
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多