18 Internationalization

18.1 Resource Bundles

A resource bundle is a Java .properties file that contains locale-specific data.

Given this Resource Bundle:

src/main/resources/io/micronaut/docs/i18n/messages_en.properties

  1. hello=Hello

src/main/resources/io/micronaut/docs/i18n/messages_es.properties

  1. hello=Hola

You can use ResourceBundleMessageSource, an implementation of MessageSource which eases accessing Resource Bundles and provides cache functionality, to access the previous messages:

ResourceBundleMessageSource Example

  1. ResourceBundleMessageSource ms = new ResourceBundleMessageSource("io.micronaut.docs.i18n.messages");
  2. assertEquals("Hola", ms.getMessage("hello", MessageSource.MessageContext.of(new Locale("es"))).get());
  3. assertEquals("Hello", ms.getMessage("hello", MessageSource.MessageContext.of(Locale.ENGLISH)).get());

ResourceBundleMessageSource Example

  1. given:
  2. ResourceBundleMessageSource ms = new ResourceBundleMessageSource("io.micronaut.docs.i18n.messages")
  3. expect:
  4. ms.getMessage("hello", MessageSource.MessageContext.of(new Locale("es"))).get() == 'Hola'
  5. and:
  6. ms.getMessage("hello", MessageSource.MessageContext.of(Locale.ENGLISH)).get() == 'Hello'

ResourceBundleMessageSource Example

  1. val ms = ResourceBundleMessageSource("io.micronaut.docs.i18n.messages")
  2. Assertions.assertEquals("Hola", ms.getMessage("hello", MessageSource.MessageContext.of(Locale("es"))).get())
  3. Assertions.assertEquals("Hello", ms.getMessage("hello", MessageSource.MessageContext.of(Locale.ENGLISH)).get())
You should not instantiate a new ResourceBundleMessageSource each time you retrieve a message. Instantiate it once, maybe in a javax.inject.Singleton, and reuse it.