Spring Boot Internationalization (i18n)
When building global applications, Spring Boot provides robust multi-language support capabilities. Its core lies in using the MessageSource interface to abstract the logic of loading different resource files, allowing developers to dynamically switch interface languages without hardcoding text. This mechanism not only enhances the localization level of the user experience but also significantly reduces maintenance costs. By configuring different property files (such as messages_zh.properties, messages_en.properties), Spring Boot can automatically return corresponding translated content based on the user's Locale (region), achieving seamless language switching functionality.
Guidelines for Building Multi-language Resource Files
To implement internationalization, it is first necessary to create standard property file formats. In a Spring Boot project, a base file named messages.properties is typically placed in the src/main/resources directory as the default configuration, followed by creating corresponding subdirectories and files for each target language. For example, you can establish structured resource paths such as i18n/zh_CN.properties, i18n/en_US.properties.
The writing of property files follows a specific key-value format. The keys (Key) usually adopt hierarchical naming conventions to simulate the structure of Java Beans, while the values (Value) contain placeholders for subsequent parameter replacement. Below is an example of a standard Chinese property file:
greeting.hello.name= Hello, {0}!welcome.message.welcome.text= Welcome to our website.
In English resource files, the keys remain completely consistent; only the value part undergoes translation processing, ensuring that the program can accurately match the corresponding language bundle during runtime. This structured design not only facilitates the management of large amounts of text content but also makes it easy to dynamically load specific language property files via code later.
Configuring Spring Boot Internationalization Support
Spring Boot automatically scans and registers the MessageSource Bean by default, but to ensure multi-language functionality works correctly, you must explicitly configure the list of supported Locales and the resource file search paths. This can be achieved by adding relevant properties to application.properties or application.yml.
If using a YAML configuration file for settings, the recommended format is as follows:
spring:
messages:
basename: classpath:i18n/messages # Specifies the location of the base resource file
fallback-to-system-locale: false # Whether to fallback to the system default language (recommended to set true)
cache-size: 50 # Cache size to avoid frequent disk reads
Additionally, you must explicitly define the list of Locales supported by the current application in application.properties:
spring.messages.enabled=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
Furthermore, it is recommended to set the default language to English (en), while allowing users to pass other language codes via the browser or frontend components. This configuration ensures that the system correctly loads the base text upon first access and quickly switches to the corresponding language resource file after receiving a specific Locale request.
Implementing Dynamic Language Retrieval and Rendering in Controllers
In actual development, the most critical step is for the backend controller (Controller) to automatically select and return the correct property value based on the user's current Locale. Spring Boot provides the LocaleContextHolder utility class to conveniently access the Locale of the current request, combined with the MessageSource.getMessage() method to complete text replacement tasks.
Here is a typical Spring MVC Controller example code:
@RestController
@RequestMapping("/api")
public class HelloController {
@Autowired
private MessageSource messageSource;
/**
* Get greeting interface
*/
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
// Construct the key, hierarchical structure corresponding to the key in the property file
Object[] args = new Object[]{name};
try {
return messageSource.getMessage("greeting.hello.name", args, null);
} catch (MissingResourceException e) {
// If the corresponding translation is not found, return the English default value or throw an exception
log.warn("Language bundle not found: {}", e.getLocale());
return "Hello!";
}
}
/**
* Get welcome message interface
*/
@GetMapping("/welcome")
public String welcome() {
Object[] args = new Object[]{"Our Website"};
try {
// If no Locale is specified, use the Locale of the current request (e.g., zh_CN)
return messageSource.getMessage("welcome.message.welcome.text", args, null);
} catch (MissingResourceException e) {
log.warn("English resource file missing: {}", e.getLocale());
return "Welcome to our website.";
}
}
}
This example demonstrates how to dynamically retrieve text using the getMessage() method and perform string replacement using placeholder parameters such as {0}, {1}, etc. When a user visits /api/hello/张三 with the browser language set to Chinese, the system returns "Hello, 张三!"; if switched to an English environment, it automatically outputs the corresponding English greeting.
Frontend Integration and User Experience Optimization Suggestions
Although the backend is responsible for providing translated text, a complete internationalization experience also requires frontend cooperation. In modern web applications, a language switcher (Language Switcher) is usually placed at the top of the page to allow users to manually change the display language of the interface. Combined with the JSON or HTML response content returned by Spring Boot, frontend frameworks such as Vue or React can listen for Locale change events and update text nodes in DOM elements in real time.
To enhance user experience, it is recommended to automatically detect the user's system language settings during initialization and negotiate an agreement with the backend. If the user has not specified a clear language preference in the browser (e.g., zh), Spring Boot can fallback to English or another default language based on its built-in rules, avoiding situations where the page displays garbled characters or remains blank. Through the collaborative work of frontend and backend, a smooth, professional, and truly multi-language web application architecture is ultimately achieved.