Internationalization with Spring
by, 11-27-2011 at 10:43 PM (2976 Views)
Often it is necessary for an application to be able to support several languages in order to address the requirements of customers located in different countries. For this java has support for what is called internationalization (i18n) that allows allows for an application to resolve text messages for different locales. The means of doing this in Java is to use what is called a ResourceBundle. These are property files that contain a key/message pair and have a special naming convention for the file name.
In Spring, the component typically used to extract messages is the MessageSource interface, which defines several methods for this task. The ApplicationContext extends the interface org.springframework.context.MessageSource. This allows for all application contexts to resolve text messages. The Spring container delegates the message resolution to a bean with the exact name messageSource. The common MessageSource implementation is org.springframework.context.ResourceBundleMessageS ource. It can be simply defined with the id messageSource and will populate itís basename(s) property with the names of the resource bundles from which you want to extract messages. An example of this is shown below:
The MessageSource is very simple to use, basically after getting the application context for the specific bundle, you can retrieve messages in the following manner:Java Code:<?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.0.xsd"> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>resourceBundleConfirmation</value> <value>resourceBundlePostprocess</value> </list> </property> </bean> </beans>
To learn more about using Springís MessageSource interface and implementations, go through the documentation.Java Code:ApplicationContext ctx = new ClassPathXmlApplicationContext("myResourceBundles.xml"); String myMessage = ctx.getMessage("queued", null, Locale.US);