Spring-MessageSource
The one of the most simplest things which you can implement in your application is MessageSource. Of course it make sense only after you have set up basic settings for a Spring MVC application. So in this tutorial I will demonstrate an example of MessageSource usage. As usually I’m going to use a java-based configuration.

Before I start the tutorial I want to make a short explanation about the MessageSourse purpose and its role in a Spring MVC application. Every web-application contains some text on its pages, e.g. page title, headers, text labels in forms… As the result you get a lot of scattered text through the application. This circumstance require some solution to make a management of static text more easier and efficient. A solution is in the topic of the article – MessageSource.

Usage of MessageSource

The first thing which I need to do to make MessageSource available in the application is to declare a bean:

...
	@Bean
	public ResourceBundleMessageSource messageSource() {
		ResourceBundleMessageSource source = new ResourceBundleMessageSource();
		source.setBasename("i18n/messages");
		source.setUseCodeAsDefaultMessage(true);
		return source;
	}
...

You can see the line where I set the base name of the MessageSource. The value is “i18n/messages” (i18n – name of the folder, messages – name of the property file). The “i18n” directory should be created in the “src/main/resources” folder. After that lets create the “messages.properties” file in the “i18n” folder:

page.header = Test page
page.greetings = Hi everyone!

After this I can use these properties in the application’s pages:

<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
...
<h1><spring:message code="page.header" /> </h1>
<p><spring:message code="page.greetings" /> </p>
...

Pay your attention on the imported “spring” tag library. In this manner you can place text in your application’s page.

Summary

The MessageSource gives you flexible solution of static text management in Spring MVC application. It makes text management more convenient, because now all text will be concentrated in the one property file. The MessageSource it is a first step to make your application internationalized (i18n). For this purpose you just need to create several property files for that locales, which your application has to support.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close