aj_blk
aj_blk

Reputation: 314

Why is that only messageSource is allowed as bean id for ResourceBundleMessageSource?

For Beans, usually we can customise the id attribute but for ResourceBundleMessageSource class, if we dont specify id="messageSource" then a exception is thrown.

<bean id="myMessageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="message" />
</bean>

It throws the Exception

Exception in thread "main" org.springframework.context.NoSuchMessageException: 

for code

new ClassPathXmlApplicationContext("springconfig.xml").getMessage("code");

Upvotes: 3

Views: 1433

Answers (2)

Duncan Jones
Duncan Jones

Reputation: 69339

Short answer - because that's the way they designed it.

As described in the reference guide:

When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source.... If the ApplicationContext cannot find any source for messages, an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above.

This is just a hard-coded value that is searched for. If you don't supply a bean with that name, you'll end up with a DelegatingMessageSource instance that won't resolve any of your messages, giving you a NoSuchMessageException.

Upvotes: 8

Andrei Stefan
Andrei Stefan

Reputation: 52368

Excerpt from the documentation:

When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source. If no message source is found, the ApplicationContext attempts to find a parent containing a bean with the same name. If it does, it uses that bean as the MessageSource. If the ApplicationContext cannot find any source for messages, an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above.

Upvotes: 3

Related Questions