将messageSource移动到applicationContext会导致默认的messageSource在dispatcher-servlet上下文中不可见

我有一个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] 

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

这有点像Spring 1.x早期的回归,从那以后从未真正改变过。

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

今天我发现“另一个”解决方案有效(对我而言,它适用于Spring 3.1但我认为它也适用于早期版本,父属性已经存在了一段时间)。 它仍将创建2个bean,但不要求您在xxx-servlet.xml文件中第二次添加整个bean定义:

在您的applicationContext.xml中:

  ...  

在xxx-servlet.xml中:

  

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