github twitter linkedin
Spring Boot Locale Resolver
2017-12-20

I had to implement locale awareness in a Spring Boot application. The client would send its preferred languages in the Accept-Language header and the application should respect that.

You can inject a Locale in your Spring MVC controller, which then should contain the locale the client has chosen.

To get Spring Boot to inject the locale from the Accept-Language header in the Locale controller parameter, install the following bean:

// Do not rename that bean, otherwise Spring MVC won't pick it up!
@Bean("localeResolver") 
public LocaleResolver acceptHeaderLocaleResolver() {
    AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();

    resolver.setDefaultLocale(Locale.GERMAN);
    resolver.setSupportedLocales(Arrays.asList(
            Locale.GERMAN,
            Locale.US,
            Locale.FRENCH
    ));

    return resolver;
}

setDefaultLocale sets the default locale, if the client doesn’t provide one. setSupportedLocales sets the supported locales. If the client sends one which isn’t supported, the default locale is used.


Back to posts