【问题标题】:Moving messageSource to applicationContext causes the default messageSource not to be visible in dispatcher-servlet context将 messageSource 移动到 applicationContext 会导致默认 messageSource 在 dispatcher-servlet 上下文中不可见
【发布时间】:2011-03-02 10:38:12
【问题描述】:

我有一个 webapp,我在 web.xml 中定义了基本的 dispatcher-servlet 上下文,它加载了 applicationContext

我在dispatcher-servlet 中定义了messageSource,并将其注入到控制器中。

我还在applicationContext 中定义了我的服务,我可以将它们注入我的控制器(在dispatcher-servlet 上下文中定义)。

但是当我将 messageSource 的定义移动到 applicationContext 以便某些服务可以解析消息时,dispatcher-servlet 上下文显示它没有找到 messageSource bean 并且正在使用默认值,因此控制器得到注入了错误的 bean。

知道为什么applicationContext 中的messageSource 定义对dispatcher-servlet 上下文不可见吗?


我看到我的 messageSource bean 已加载到日志的 applicationContext 部分:
2058 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating shared instance of singleton bean 'messageSource'
2058 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Creating instance of bean 'messageSource'
...
2082 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext  - Using MessageSource [mycommons.spring.ResourceBundleMessageSourceWithDefaultResolution: basenames=[messages]]


我在dispatcher-servlet的加载中看到了这个日志:

3858 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext  - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@55611ed3]

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    这就是它的工作方式。 messageSource bean 必须在要使用它的上下文中定义。它不会从父上下文“继承”到子上下文。

    这有点回溯到 Spring 1.x 的早期,并且从那以后从未真正改变过。

    有许多“魔豆”必须直接驻留在 servlet appcontext 中,这就是其中之一。

    【讨论】:

    • 啊哈,春天的魔法有时会吸引我。 :) 谢谢!你知道最好的解决方法吗?还是我只需要将控制器使用的消息与服务可能使用的消息分开?
    • @David:您可以将它们分开,也可以将messageSource bean 定义放入单独的 XML 文件中,并在需要的地方包含它(使用 <import resource="...">)。
    • 我假设将 添加到 dispatcher-servlet 和 applicationContext 将创建 messageSource bean 的两个副本。
    • @David 是的,它会的。不过,这应该是无害的。
    • 可以通过调用delegatingMessageSource.getParentMessageSource()来获取childContext中的父messageSource
    【解决方案2】:

    今天我找到了“另一种”可行的解决方案(对我来说,它适用于 Spring 3.1,但我认为它也适用于早期版本, parent 属性已经存在了一段时间)。它仍然会创建 2 个 bean,但不需要您在 xxx-servlet.xml 文件中再次添加整个 bean 定义:

    在您的 applicationContext.xml 中:

    <bean id="baseMessageSource" class="org.springframework...YourMessageSourceClass">
       ...
    </bean>
    

    在你的 xxx-servlet.xml 中:

    <bean id="messageSource" parent="baseMessageSource" />
    

    第二个引用将简单地从您的应用程序上下文中“克隆”基本 bean,并使其可用于您的 servlet/控制器等。这样,您甚至可以覆盖 servlet 中的部分消息源配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多