Quick tutorial to getting messages from resource bundles

If you need to get messages dependent on locale setting and you are using Spring Framework, you are able to use ResourceBundleMessageSource and localize them very quickly.

At first, we will create a Resource Bundle files named with lang postfix to Resource folder:

Resource bundle structure

Next step will be that to say our application about that we want start using ResourceBundleMessageSource bean. Pay attention to value in property. Here we will defined that where we have our message files and how we named them. If you want to keep them directly under resource folder, delete locale. part, but if you are planning to have a more resources for your application, it is always better to keep little bit more detailed structure:

 <bean id="messageSource" class="">
  <property name="basename">

And now we are able to use it! We autowired our bean to our class where we want to get our localized messages by classic @Autowired annotation:

private ResourceBundleMessageSource messageSource;

For this example I choosed only throwing localized exception, but of course, getMessage method return String which you are able to use everywhere you want.

This is key-value for file:

myapp.exception.test=Testing message to throw

Now you are able to throw it by this:

throw new Exception(messageSource.getMessage("myapp.exception.test", null, Locale.US));

Second parameter is null (it is used for passing parameters to message) and third we set hard as Locale.US. ResourceBundleMessageSource bean will look up for file with postfix defined by en or en_US. In real word you will need to getting locale variable from user and a lot of messages will be parametrized.


project.test.error.whatever=Hello {0}, this is your message for {1}. Goodbay {0}!

This is example of parametrized message in We are using {0} and {1} as placeholders for variables, which we will pass via getMessage method.

public class Test{
private ResourceBundleMessageSource messageSource;

  public void callMyLocalizedMessage(){
    Locale locale = new Locale("en", "US"); // Default locale - set to en language and US country
    // Some code to get locales from front-end, properties or user input
    String param01 = "John";
    String param02 = "Elise";
    // Here is some code to get params - i.e. from DAO, etc...

    String[] args = {param01, param02};
    throw new Exception(messagesource.getMessage("project.test.error.whatever", args, MiscUtils.getUserLocale(security));

Output is throwed exception with content _Hello John, this is your message for Elise. Goodbay John!_

Leave a Reply

Your email address will not be published. Required fields are marked *