Moving messageSource to applicationContext causes messageSource to not display by default in the context of the servlet manager

I have a webapp in which I define the base dispatcher-servlet context in web.xml and it loads the applicationContext .

I had a messageSource defined in dispatcher-servlet and it injected it into the controllers in order.

I also have my services defined in applicationContext , and I can embed them in my controllers (defined in the context of dispatcher-servlet ).

But when I moved my definition for messageSource to applicationContext so that some services can allow messages, the dispatcher-servlet context shows that it does not find the messageSource bean and uses the default value, the controllers get the wrong bean.

Any idea why the definition of messageSource in applicationContext will not be displayed in dispatcher-servlet context?


I see that my messageSource bean is loading in the applicationContext section of the logs:
 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]] 


I see this log in dispatcher-servlet loading:

 3858 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [ org.springframework.context.support.DelegatingMessageSource@5561 1ed3] 
+7
source share
2 answers

This is how it works. messageSource bean must be defined in the context in which it should be used. It will not be "inherited" from the parent context to the child.

This is a bit of a return to the early days of Spring 1.x, and has never changed since.

There are several โ€œmagic beansโ€ that need to be resident directly in the servlet appsettext, and this is one of them.

+11
source

Today I found a โ€œdifferentโ€ solution that works (for me, this works in Spring 3.1, but I assume that it will work in earlier versions too, the parent attribute has been around for some time). It will still create 2 beans, but does not require you to add the full bean definition a second time in the xxx-servlet.xml file:

In your applicationContext.xml:

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

In your xxx-servlet.xml:

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

The second link simply "clones" the bean base from the context of your application and makes it accessible to your servlet / controllers, etc. That way, you can even override portions of the message source configuration in the servlet.

+1
source

All Articles