Spring MessageSourceAware Java Bean Example

If you want to access i18n resources bundles for different locales into your java source code, then that java class must implement MessageSourceAware interface. After implementing MessageSourceAware interface, spring context will automatically inject the MessageSource reference into the class via setMessageSource(MessageSource messageSource) setter method which your class need to implement.

How to access MessageSource in spring bean

As mentioned, make your bean class MessageSourceAware as given way.

package com.howtodoinjava.demo.controller;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

@Controller
public class EmployeeController implements MessageSourceAware
{
	private MessageSource messageSource;
 
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void readLocaleSpecificMessage()
	{
	String englishMessage = messageSource.getMessage("first.name", null, Locale.US);
 
    	System.out.println("First name label in English : " + englishMessage);
 
    	String chineseMessage = messageSource.getMessage("first.name", null, Locale.SIMPLIFIED_CHINESE);
    	 
    	System.out.println("First name label in Chinese : " + chineseMessage);
	}
}

Now there are two properties files in “resources” folder in web application. (Files should be in classpath in runtime).

messages_en_US.properties and messages_zh_CN.properties

#messages_en_US.properties
first.name=FirstName in English

#messages_zh_CN.properties
first.name=FirstName in Chinese

Now test if we are able to load locale specific properties.

package springmvcexample;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.howtodoinjava.demo.controller.EmployeeController;

public class TestSpringContext 
{
	@SuppressWarnings("resource")
	public static void main(String[] args) 
	{
		ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "/spring-servlet.xml" });

		EmployeeController controller = (EmployeeController) context.getBean(EmployeeController.class);
		
		controller.readLocaleSpecificMessage();
	}
}

Output:

First name label in English : FirstName in English
First name label in Chinese : FirstName in Chinese

Clearly, we are able to access resources in locale specific manner inside java bean.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.