Spring Internationalization Resource Bundle Examples

Spring framework support internationalization. With this function, you can display text messages in different languages to different locale request users. For example. display English text to US users and Chinese text to china users. This article will show you how to achieve this in Spring.

1. Create Different Locale Text Message Properties File.

  1. Before coding, we should first create the text message properties file for the different locales. They are all saved in the src/main/resources/locale folder.
  2. And all the filename-prefix is message, this is called message bundle source basename. Below are some examples.
  3. message_en_US.properties: Save message display to US Locale user.
  4. message_zh_CN.properties: Save message display to China Locale user.
  5. message_en.properties: Save message display to English Locale user.
  6. message.properties: This is the default message properties file, if no locale is specified then show messages saved in this file.
  7. Content in the above file is key = value pairs format like below. {0} and {1} are placeholders that will be replaced by String parameters in java codes.
    welcome.info=Hello {0}, you are welcome to {1}. This is an English web site.
  8. For east Asia languages such as Chinese, you should execute the command C:\Java\jdk1.8.0_131\bin\native2ascii.exe to convert the Chinese language to Unicode. If you use Eclipse, the editor can convert it automatically.
  9. Content in message_zh_CN.properties after converting Chinese words to Unicode.
    welcome.info=\u4F60\u597D {0}, \u6B22\u8FCE\u6765\u5230 {1}. \u8FD9\u662F\u7F51\u7AD9\u4E2D\u6587\u7248\u672C.

2. Get Messages By MessageSource Interface In ApplicationContext.

  1. The interface org.springframework.context.MessageSource provides methods to get the message by locale, and the interface ApplicationContext just extends it, so we can use ApplicationContext.getMessage(String messageKey, String paramsArrp[], Locale locale) to get related messages.
  2. Create application context XML file ResourceBeanSettings.xml in src/main/resources folder.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\SPRINGEXAMPLEPROJECT
    │  .classpath
    │  .project
    │  .springBeans
    │  pom.xml
    │
    ├─.settings
    │      org.eclipse.core.resources.prefs
    │      org.eclipse.jdt.core.prefs
    │      org.eclipse.m2e.core.prefs
    │
    ├─src
    │  └─main
    │      └─resources
    │          │  ResourceBeanSettings.xml
    │          │
    │          ├─locale
    │          │      message.properties
    │          │      message_en.properties
    │          │      message_en_US.properties
    │          │      message_zh_CN.properties
  3. Add below bean definition, the bean id must be messageSource otherwise an Exception will be thrown. The basename should include directory path relative to src/main/resources.
  4. The class org.springframework.context.support.ResourceBundleMessageSource just implement the interface MessageSource, it is commonly used to retrieve different locale resource bundles messages.
        <!-- The bean id must be messageSource otherwise an Exception maybe occurred during execution. --> 
        <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
             <!-- This is text message properties file prefix, in this example is locale\message. --> 
             <property name="basename"> <value>locale\message</value> </property> 
        </bean>
  5. ResourceBundleMessageSourceExample.java
    public class ResourceBundleMessageSourceExample {
    
    	public static void main(String[] args) {
    		
    	   	// Initiate Spring application context.
    		ApplicationContext springAppCtx = new ClassPathXmlApplicationContext("ResourceBeanSettings.xml");
    		
    		/* Declare text message input parameters value. 
    		 * These String value will be inserted at {0} and {1} placeholder in text message by index. */
    		String paramsArray[] = {"Jerry","dev2qa.com"};
    		
    		/* Get US locale message. */
    		String message = springAppCtx.getMessage("welcome.info", paramsArray, Locale.US);
    		System.out.println(message);
    		
    		/* Get English locale message. */
    		message = springAppCtx.getMessage("welcome.info", paramsArray, Locale.ENGLISH);
    		System.out.println(message);
    		
    		/* Get China locale message. */
    		message = springAppCtx.getMessage("welcome.info", paramsArray, Locale.CHINA);
    		System.out.println(message);
    		
    		/* Get default locale. */
    		Locale defaultLocale = Locale.getDefault();
    		message = springAppCtx.getMessage("welcome.info", paramsArray, defaultLocale);
    		System.out.println(message);
    
    	}
    
    }
    
  6. Above code execution output.
    Hello Jerry, you are welcome to dev2qa.com. This is an English web site for USA.
    Hello Jerry, you are welcome to dev2qa.com. This is an English web site.
    你好Jerry, 欢迎来到dev2qa.com. 这是网站中文版本.
    你好Jerry, 欢迎来到dev2qa.com. 这是网站中文版本.

3. Get Messages In Spring Bean By Implement MessageSourceAware.

  1. If you want to get resource messages in Spring bean, you can make the bean implement the interface MessageSourceAware.
  2. And then override its method setMessageSource(MessageSource messageSource). Spring framework will inject a MessageSource object into it automatically.
  3. MessageSourceAwareExample.java
    public class MessageSourceAwareExample implements MessageSourceAware {
    
    	// This is private MessageSource object.
    	private MessageSource messageSource;
    	
    	public MessageSource getMessageSource() {
    		return messageSource;
    	}
    
    	// Spring framework inject MessageSource object automatically.
    	@Override
    	public void setMessageSource(MessageSource messageSource) {
    		// Assign system injected object to local variable for using in other methods.
    		this.messageSource = messageSource;
    	}
    
    	public static void main(String[] args) {
    		
    	   	// Initiate Spring application context.
    		ApplicationContext springAppCtx = new ClassPathXmlApplicationContext("ResourceBeanSettings.xml");
    		
    		MessageSourceAwareExample messageSourceAwareExampleBean = (MessageSourceAwareExample)springAppCtx.getBean("messageSourceAwareExampleBean");
    		
    		/* Declare text message input parameters value. 
    		 * These String values will be inserted at {0} and {1} placeholder in text message by index. */
    		String paramsArray[] = {"Elon","dev2qa.com"};
    		
    		/* Get US locale message. */
    		String message = messageSourceAwareExampleBean.getMessageSource().getMessage("welcome.info", paramsArray, Locale.US);
    		System.out.println(message);
    		
    		/* Get English locale message. */
    		message = messageSourceAwareExampleBean.getMessageSource().getMessage("welcome.info", paramsArray, Locale.ENGLISH);
    		System.out.println(message);
    		
    		/* Get China locale message. */
    		message = messageSourceAwareExampleBean.getMessageSource().getMessage("welcome.info", paramsArray, Locale.CHINA);
    		System.out.println(message);
    		
    		/* Get default locale. */
    		Locale defaultLocale = Locale.getDefault();
    		message = messageSourceAwareExampleBean.getMessageSource().getMessage("welcome.info", paramsArray, defaultLocale);
    		System.out.println(message);
    	}
    
    }
    
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x