Internationalization (i18n) and localization (l10n) are important features for applications that need to support multiple languages and cultures. In a Spring Boot application, there are several ways to implement i18n and l10n, but the most common approach is to use Spring’s message source and locale resolver.
Here are the steps to implement i18n and l10n in a Spring Boot application:
Configure a message source: In a Spring Boot application, you can use the MessageSource interface to provide localized messages. To configure a message source, you can create a bean that implements the MessageSource interface and specifies the location of the message properties files. Here’s an example:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
In this example, the message properties files are located in the classpath:messages directory.
Configure a locale resolver: To determine the user’s preferred language and culture, you can use the LocaleResolver interface. In a Spring Boot application, you can configure a locale resolver by creating a bean that implements the LocaleResolver interface. Here’s an example:
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
In this example, the locale resolver uses the Accept-Language header in the HTTP request to determine the user’s preferred language and culture.
Use message keys in your application: In your application, you can use message keys to reference the localized messages defined in the message properties files. For example, instead of hard-coding the message text in your code, you can use a message key like this:
@GetMapping("/hello")
public String hello(@RequestHeader(value = "Accept-Language", required = false) Locale locale) {
return messageSource.getMessage("hello.message", null, locale);
}
In this example, the getMessage method of the message source is used to retrieve the localized message with the key hello.message. The locale parameter is used to determine the user’s preferred language and culture.
With these steps, you can implement i18n and l10n in your Spring Boot application using Spring’s message source and locale resolver. By defining your messages in separate properties files and using message keys in your application code, you can easily support multiple languages and cultures.