6.7 Locale Resolution

Micronaut supports several strategies for resolving locales for a given request. The getLocale— method is available on the request, however it only supports parsing the Accept-Language header. For other use cases where the locale can be in a cookie, the user’s session, or should be set to a fixed value, HttpLocaleResolver can be used to determine the current locale.

The LocaleResolver API does not need to be used directly. Simply define a parameter to a controller method of type java.util.Locale and the locale will be resolved and injected automatically.

There are several configuration options to control how to resolve the locale:

🔗

Table 1. Configuration Properties for HttpLocaleResolutionConfigurationProperties
PropertyTypeDescription

micronaut.server.locale-resolution

HttpServerConfiguration$HttpLocaleResolutionConfigurationProperties

The locale resolution configuration

micronaut.server.locale-resolution.fixed

java.util.Locale

Set the language tag for the locale. Supports BCP 47 language tags (e.g. “en-US”) and ISO standard (e.g “en_US”).

micronaut.server.locale-resolution.session-attribute

java.lang.String

Sets the key in the session to look for the locale.

micronaut.server.locale-resolution.cookie-name

java.lang.String

Sets the name of the cookie that is used to store the locale.

micronaut.server.locale-resolution.header

boolean

Set to true if the locale should be resolved from the Accept-Language header. Default value (true).

micronaut.server.locale-resolution.default-locale

java.util.Locale

Sets the locale that will be used if the locale cannot be resolved through any means. Defaults to the system default.

Locales can be configured in the “en_GB” format, or in the BCP 47 (Language tag) format. If multiple methods are configured, the fixed locale takes precedence, followed by session/cookie, then header.

If any of the built-in methods do not meet your use case, create a bean of type HttpLocaleResolver and set its order (through the getOrder method) relative to the existing resolvers.