我有一个webapp,我在其中定义了web.xml中的基本dispatcher-servlet
上下文,并加载了applicationContext
。
我在messageSource
中定义了dispatcher-servlet
,并将其注入控制器。
我也在applicationContext
中定义了我的服务,我可以将它们注入我的控制器(在dispatcher-servlet
上下文中定义)。
但当我将messageSource
的定义移至applicationContext
以便某些服务可以解析消息时,dispatcher-servlet
上下文显示它找不到messageSource
bean并且使用默认值,因此控制器会注入错误的bean。
知道为什么applicationContext
中的messageSource定义对dispatcher-servlet
上下文不可见?
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]
答案 0 :(得分:13)
这就是它的工作方式。 messageSource
bean 必须在要使用它的上下文中定义。它不会从父上下文“继承”到子项。
这有点像Spring 1.x早期的回归,从那以后就没有真正改变过。
有许多“魔豆”必须直接驻留在servlet appcontext中,这就是其中之一。
答案 1 :(得分:1)
今天我发现“另一个”解决方案有效(对我而言,它适用于Spring 3.1但我认为它也适用于早期版本,父属性已经存在了一段时间)。它仍将创建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中部分消息源配置。