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
hello=Hello
src/main/resources/io/micronaut/docs/i18n/messages_es.properties
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
ResourceBundleMessageSource ms = new ResourceBundleMessageSource("io.micronaut.docs.i18n.messages");
assertEquals("Hola", ms.getMessage("hello", MessageSource.MessageContext.of(new Locale("es"))).get());
assertEquals("Hello", ms.getMessage("hello", MessageSource.MessageContext.of(Locale.ENGLISH)).get());
ResourceBundleMessageSource Example
given:
ResourceBundleMessageSource ms = new ResourceBundleMessageSource("io.micronaut.docs.i18n.messages")
expect:
ms.getMessage("hello", MessageSource.MessageContext.of(new Locale("es"))).get() == 'Hola'
and:
ms.getMessage("hello", MessageSource.MessageContext.of(Locale.ENGLISH)).get() == 'Hello'
ResourceBundleMessageSource Example
val ms = ResourceBundleMessageSource("io.micronaut.docs.i18n.messages")
Assertions.assertEquals("Hola", ms.getMessage("hello", MessageSource.MessageContext.of(Locale("es"))).get())
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. |