By default, Spring Boot auto-configures AcceptHeaderLocaleResolver, which resolves the locale from the request's Accept-Language header. This tutorial shows two ways to change that default: registering your own LocaleResolver bean, or using configuration properties.
Option 1: Registering a Custom LocaleResolver Bean
If your application defines its own LocaleResolver bean, Spring Boot's auto-configuration backs off and uses that bean instead. For example, to resolve the locale from the user's session rather than the request header:
@Configuration
public class WebConfig {
@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver r = new SessionLocaleResolver();
r.setDefaultLocale(Locale.US);
return r;
}
}
Any implementation of LocaleResolver can be used here — SessionLocaleResolver, CookieLocaleResolver, or a custom implementation of your own. Once this bean is present, it takes priority over the auto-configured default.
Option 2: Using Configuration Properties
For the simpler case of pinning the application to one fixed locale, without writing any Java code, Spring Boot exposes two properties:
spring.mvc.locale-resolver=fixed
spring.mvc.locale=fr_FR
spring.mvc.locale-resolver=fixed switches the auto-configured resolver to FixedLocaleResolver, and spring.mvc.locale sets the locale it always resolves to. This approach doesn't support changing the locale per request or per user — it's meant for applications that only ever need a single, fixed locale. For anything more dynamic (like letting a user pick their language), use Option 1 instead.
If interested, check out the method localeResolver() of WebMvcAutoConfiguration.java to see how Spring Boot decides between the auto-configured default, the fixed-locale properties, and any custom bean you provide.
|