HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Spring i18n – ResourceBundleMessageSource

By Lokesh Gupta | Filed Under: Spring Core

For an application to support internationalization (i18n), it requires the capability of resolving text messages for different locales. Spring’s application context is able to resolve text messages for a target locale by their keys. Typically, the messages for one locale should be stored in one separate properties file. This properties file is called a resource bundle.

MessageSource is an interface that defines several methods for resolving messages. The ApplicationContext interface extends this interface so that all application contexts are able to resolve text messages.

An application context delegates the message resolution to a bean with the exact name messageSource. ResourceBundleMessageSource is the most common MessageSource implementation that resolves messages from resource bundles for different locales.

1. Resolve messages using ResourceBundleMessageSource

As an example, you can create the following resource bundle, messages_en_US.properties, for the English language in the United States. Resource bundles will be loaded from the root of the classpath.

1.1. Create resource bundle

Create a file name messages_en_US.properties in classpath of your spring application.

msg.text=Welcome to howtodoinjava.com

1.2. Configure ResourceBundleMessageSource bean

Now configure ResourceBundleMessageSource class as bean name "messageSource". Additionally, you have to specify the base name of the resource bundles for ResourceBundleMessageSource.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>messages</value>
    </property>
</bean>

2. Resource Bundle Lookup Order

  1. For this messageSource definition, if you look up a text message for the United States locale, whose preferred language is English, the resource bundle messages_en_US.properties, which matches both the language and country, will be considered first.
  2. If there’s no such resource bundle or the message can’t be found, the one messages_en.properties that matches the language only will be considered.
  3. If this resource bundle still can’t be found, the default messages.properties for all locales will be chosen finally.

3. Demo – How to use MessageSource

3.1. Fetch the message directly

Now to check if messages can be loaded or not, run this code:

public class TestSpringContext 
{
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception 
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        String message = context.getMessage("msg.text", null, Locale.US);
        
        System.out.println(message);
    }
}

Output:

Welcome to howtodoinjava.com

3.2. Implement MessageSourceAware interface in beans

Great, so we are able to resolve messages. BUT, here we are directly accessing ApplicationContext so it looks easy. If we want to access messages in some bean instance then we will need to implement either the ApplicationContextAware interface or the MessageSourceAware interface.

Something like this:

public class EmployeeController implements MessageSourceAware {

    private MessageSource messageSource;

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    //Other code
}

Now you can use this messageSource instance to retrieve / resolve the text messages defined in resource files.

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

3
Leave a Reply

This comment form is under antispam protection
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Akash

Getting below error:

17:28:10.637 [main] DEBUG org.springframework.beans.factory.xml.DefaultDocumentLoader - 
Using JAXP provider [com.sun.org.apache.xerces.internal. jaxp.DocumentBuilderFactoryImpl]
Exception in thread "main" org.springframework.beans.factory. xml.XmlBeanDefinitionStoreException: 
Line 1 in XML document from class path resource [applicationContext.xml] is invalid; 
nested exception is org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 98; cvc-elt.1: 

Cannot find the declaration of element 'bean'

Where did you declare the messageSource bean, in the project?

Vote Up0Vote Down  Reply
1 year ago
Fabrice

Thank you!

Vote Up0Vote Down  Reply
4 years ago
Binh Thanh Nguyen

Thanks, nice tips,

Vote Up0Vote Down  Reply
4 years ago

Search Tutorials

Spring Tutorial

  • Spring – Introduction
  • Spring – IoC Containers
  • Spring – IoC vs. DI
  • Spring – Bean Scopes
  • Spring – Bean Life Cycle
  • Spring – Bean Postprocessors
  • Spring – Autowiring
  • Spring – Annotations
  • Spring – Stereotype Annotations
  • Spring – Task Scheduling
  • Spring – Timer Task
  • Spring – Events
  • Spring – Message Source
  • Spring – ResourceLoader
  • Spring – Property Editor
  • Spring – Send Email
  • Spring – Version-less Schema
  • Spring – Interview Questions
  • Spring – Best Practices

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz