如何将SpringBoot项目的国际化流程优化为高效?
摘要:在 Spring Boot 项目已经开发完成后,想要实现国际化(i18n),让所有提示信息(后端返回的错误消息、成功消息、异常信息、枚举描述等)支持多语言,处理流程如下: 1. 创建国际化资源文件(messages.properties)
在 Spring Boot 项目已经开发完成后,想要实现国际化(i18n),让所有提示信息(后端返回的错误消息、成功消息、异常信息、枚举描述等)支持多语言,处理流程如下:
1. 创建国际化资源文件(messages.properties)
在 src/main/resources 目录下(新建 i18n 子目录),创建以下文件:
1 src/main/resources/
2 └── i18n/
3 ├── messages.properties # 默认语言(通常是中文或英文)
4 ├── messages_zh_CN.properties # 简体中文
5 ├── messages_en_US.properties # 美式英文
6 ├── messages_zh_TW.properties # 繁体中文(可选)
7 └── messages_ja.properties # 日语(可选)
messages.properties(中文示例):
1 # 通用提示
2 success=操作成功
3 error.system=系统异常,请稍后重试
4 error.notfound=资源不存在
5
6 # 业务提示
7 user.login.success=登录成功
8 user.login.fail=用户名或密码错误
9 user.notfound=用户不存在
messages_en_US.properties(英文示例):
1 success=Operation successful
2 error.system=System error, please try again later
3 error.notfound=Resource not found
4
5 user.login.success=Login successful
6 user.login.fail=Username or password is incorrect
7 user.notfound=User not found
注意:
文件名必须以 messages 开头(Spring Boot 默认查找规则)。
所有提示统一放在 i18n 目录下,方便管理。
2. 配置 application.yml(或 application.properties)
1 # application.yml
2 spring:
3 messages:
4 basename: i18n/messages # 资源文件基础名(支持通配符)
5 encoding: UTF-8 # 必须是 UTF-8
6 fallback-to-system-locale: false # 推荐设置为 false(找不到对应语言时不回退到系统默认Locale)
7 use-code-as-default-message: true # 找不到key时直接返回code(调试方便,上线可改为false)
1 # properties
2 spring.messages.basename=i18n/messages
3 spring.messages.encoding=UTF-8
4 spring.messages.fallback-to-system-locale=false
5 spring.messages.use-code-as-default-message=true
3. 自定义 LocaleResolver 和 LocaleChangeInterceptor(支持前端传参切换语言)
Spring Boot 默认使用 AcceptHeaderLocaleResolver(根据请求头 Accept-Language 自动识别),生产环境通常还需要支持通过参数或 cookie 切换语言。
