public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:appContext/messageSource.xml");
ctx.refresh();
Locale english = Locale.ENGLISH;
Locale czech = new Locale("cs", "CZ");
System.out.println(ctx.getMessage("msg", null, english));
System.out.println(ctx.getMessage("msg", null, czech));
System.out.println(ctx.getMessage("nameMsg", new Object[] { "Clarence",
"Ho" }, english));
}
}
Don't worry about the calls to getMessage() just yet; we return to those shortly. For now, just know
that they retrieve a keyed message for the locale specified. In Listing 5-34 you can see the configuration
used by this application (appContext/messageSource.xml).
Listing 5-34. Configuring a MessageSource Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>buttons</value>
<value>labels</value>
</list>
</property>
</bean>
</beans>
Here we are defining a ResourceBundleMessageSource bean with the name messageSource as required
and configuring it with a set of names to form the base of its file set. A Java ResourceBundle, which is used
by ResourceBundleMessageSource, works on a set of properties files that are identified by base names.
When looking for a message for a particular Locale, the ResourceBundle looks for a file that is named as a
combination of the base name and the locale name. For instance, if the base name is foo and we are
looking for a message in the en-GB (British English) locale, then the ResourceBundle looks for a file called
foo_en_GB.properties.
For the previous example, the content of the properties files for English (labels_en.properties) and
Czech (labels_cs_CZ.properties) are shown in Listing 5-35 and Listing 5-36, respectively.
Listing 5-35. labels_en.properties File
msg=The quick brown fox jumped over the lazy dog
nameMsg=My name is {0} {1}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home