spring項(xiàng)目實(shí)現(xiàn)國際化流程解析
在 Spring Boot 項(xiàng)目已經(jīng)開發(fā)完成后,想要實(shí)現(xiàn)國際化(i18n),讓所有提示信息(后端返回的錯(cuò)誤消息、成功消息、異常信息、枚舉描述等)支持多語言,處理流程如下:
1. 創(chuàng)建國際化資源文件(messages.properties)
在 src/main/resources 目錄下(新建 i18n 子目錄),創(chuàng)建以下文件:
src/main/resources/
└── i18n/
├── messages.properties # 默認(rèn)語言(通常是中文或英文)
├── messages_zh_CN.properties # 簡體中文
├── messages_en_US.properties # 美式英文
├── messages_zh_TW.properties # 繁體中文(可選)
└── messages_ja.properties # 日語(可選)messages.properties(中文示例):
# 通用提示 success=操作成功 error.system=系統(tǒng)異常,請稍后重試 error.notfound=資源不存在 # 業(yè)務(wù)提示 user.login.success=登錄成功 user.login.fail=用戶名或密碼錯(cuò)誤 user.notfound=用戶不存在
messages_en_US.properties(英文示例):
success=Operation successful error.system=System error, please try again later error.notfound=Resource not found user.login.success=Login successful user.login.fail=Username or password is incorrect user.notfound=User not found
注意:
- 文件名必須以 messages 開頭(Spring Boot 默認(rèn)查找規(guī)則)。
- 所有提示統(tǒng)一放在 i18n 目錄下,方便管理。
2. 配置 application.yml(或 application.properties)
# application.yml
spring:
messages:
basename: i18n/messages # 資源文件基礎(chǔ)名(支持通配符)
encoding: UTF-8 # 必須是 UTF-8
fallback-to-system-locale: false # 推薦設(shè)置為 false(找不到對應(yīng)語言時(shí)不回退到系統(tǒng)默認(rèn)Locale)
use-code-as-default-message: true # 找不到key時(shí)直接返回code(調(diào)試方便,上線可改為false)# properties spring.messages.basename=i18n/messages spring.messages.encoding=UTF-8 spring.messages.fallback-to-system-locale=false spring.messages.use-code-as-default-message=true
3. 自定義 LocaleResolver 和 LocaleChangeInterceptor(支持前端傳參切換語言)
Spring Boot 默認(rèn)使用 AcceptHeaderLocaleResolver(根據(jù)請求頭 Accept-Language 自動識別),生產(chǎn)環(huán)境通常還需要支持通過參數(shù)或 cookie 切換語言。
使用 SessionLocaleResolver + LocaleChangeInterceptor:
@Configuration
public class LocaleConfig implements WebMvcConfigurer {
// 默認(rèn)語言
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // 默認(rèn)簡體中文
return localeResolver;
}
// 攔截器:支持 ?lang=zh_CN 或 ?lang=en_US 切換語言
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang"); // 前端傳參名
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}若優(yōu)先從請求頭識別,再支持參數(shù)切換,可以自定義 LocaleResolver(更靈活)。
4. 在代碼中使用 MessageSource 獲取國際化消息
方式一:注入 MessageSource
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private MessageSource messageSource;
@GetMapping("/test")
public ResponseEntity<String> test(Locale locale) { // Locale 可選從參數(shù)注入
// 方式1:直接使用 locale 參數(shù)
String msg = messageSource.getMessage("user.login.success", null, locale);
// 方式2:從 LocaleContextHolder 獲取當(dāng)前語言(推薦?。?
String msg2 = messageSource.getMessage("user.login.success", null, LocaleContextHolder.getLocale());
return ResponseEntity.ok(msg2);
}
}方式二:統(tǒng)一封裝工具類
@Component
public class MessageUtils {
private static MessageSource messageSource;
@Autowired
public void setMessageSource(MessageSource messageSource) {
MessageUtils.messageSource = messageSource;
}
/**
* 獲取國際化消息
*/
public static String getMessage(String code, Object... args) {
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
public static String getMessage(String code) {
return getMessage(code, (Object) null);
}
}使用方式:
throw new BusinessException(MessageUtils.getMessage("user.notfound"));
// 或
return Result.error(MessageUtils.getMessage("error.system"));5. 全局異常處理中使用國際化
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result<?> handleBusinessException(BusinessException e) {
// 假設(shè) BusinessException 里面存了 messageCode
String message = MessageUtils.getMessage(e.getCode(), e.getArgs());
return Result.error(message);
}
@ExceptionHandler(Exception.class)
public Result<?> handleException(Exception e) {
return Result.error(MessageUtils.getMessage("error.system"));
}
}6. 支持參數(shù)占位符
# messages.properties
user.age.limit=年齡必須在 {0} 到 {1} 歲之間 String msg = MessageUtils.getMessage("user.age.limit", 18, 60);
// 輸出:年齡必須在 18 到 60 歲之間7. 常見最佳實(shí)踐總結(jié)
| 處理點(diǎn) | 處理方式 |
|---|---|
| 資源文件位置 | src/main/resources/i18n/messages_*.properties |
| 默認(rèn)語言 | 簡體中文(Locale.SIMPLIFIED_CHINESE) |
| 語言切換方式 | 請求頭 Accept-Language + ?lang=zh_CN |
| 消息獲取方式 | 優(yōu)先使用 LocaleContextHolder.getLocale() |
| 工具類 | 封裝 MessageUtils 統(tǒng)一獲取 |
| 異常消息 | 全部使用 code + MessageUtils 獲取 |
| 找不到key | 建議 use-code-as-default-message=false |
| 編碼 | 必須 UTF-8 |
8. 測試方法
- 瀏覽器開發(fā)者工具 → Network → 修改請求頭 Accept-Language: en-US,en;q=0.9
- 或直接在 URL 后加 ?lang=en_US
完成以上步驟,你的 Spring Boot 項(xiàng)目就實(shí)現(xiàn)了標(biāo)準(zhǔn)的國際化支持,所有提示信息都可以根據(jù)用戶語言自動切換。
到此這篇關(guān)于spring項(xiàng)目國際化流程的文章就介紹到這了,更多相關(guān)spring項(xiàng)目國際化流程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java.sql.SQLException問題解決以及注意事項(xiàng)
這篇文章主要給大家介紹了關(guān)于java.sql.SQLException問題解決以及注意事項(xiàng)的相關(guān)資料,這個(gè)問題其實(shí)很好解決,文中通過圖文將解決的辦法介紹的很詳細(xì),需要的朋友可以參考下2023-07-07
關(guān)于Spring MVC框架中攔截器Interceptor的使用解讀
這篇文章主要介紹了關(guān)于Spring MVC框架中攔截器Interceptor的使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
梳理總結(jié)Java?static關(guān)鍵字的方法作用
這篇文章主要介紹了梳理總結(jié)Java?static關(guān)鍵字的方法作用,?static?關(guān)鍵字可以用來修飾的成員變量和成員方法,被修飾的成員是屬于類的,而不是單單是屬于某個(gè)對象的2022-06-06
java redis 實(shí)現(xiàn)簡單的用戶簽到功能
這篇文章主要介紹了java redis 實(shí)現(xiàn)簡單的用戶簽到功能,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12
Java在OJ時(shí)運(yùn)行超時(shí)的問題解決方案
Java語言什么都好,就是在OJ的時(shí)候真的是太慢了,今天來講解一種讓Java運(yùn)行速度快速提高的方法,感興趣的朋友一起看看吧2023-11-11
詳解Java線程池隊(duì)列中的延遲隊(duì)列DelayQueue
這篇文章主要為大家詳細(xì)介紹了Java線程池隊(duì)列中的延遲隊(duì)列DelayQueue的相關(guān)資料,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-12-12

