SpringBoot3項目實現(xiàn)國際化的示例詳解
下面小編就來和大家簡單介紹一下springBoot3 項目實現(xiàn)國際化的完整代碼吧
1 創(chuàng)建國際化資源文件
//src/main/resources/i18n/Resource Bundle 'messages'
messages.properties (默認(rèn))
messages_en_US.properties (英文)
messages_zh_CN.properties (中文)
// 翻譯文件內(nèi)容:
# {}是參數(shù)引用,用于拼接傳參
user.password.retry.limit.exceed=密碼輸入錯誤{0}次,帳戶鎖定{1}分鐘
2 配置 application.yml
# Spring配置
spring:
# 資源信息
messages:
# 國際化資源文件路徑,如果有多個通過逗號隔開,這里的messages不是路徑,而是文件名前綴
basename: i18n/messages
encoding: UTF-8
3 維護(hù) i8n 配置類
package com.okyun.framework.config;
?
/**
* 資源文件配置加載
* 語言切換優(yōu)先級 -> 1 請求lang參數(shù)語言 -> 2 瀏覽器設(shè)置的默認(rèn)語言 -> 3 該系統(tǒng)默認(rèn)語言(簡體中文)
*
* @author hubiao
*/
@Configuration
public class I18nConfig implements WebMvcConfigurer
{
/**
* 語言切換
* @return
*/
@Bean
public LocaleResolver localeResolver()
{
// SessionLocaleResolver 用來解析和存儲用戶的 Locale 信息在會話 (session) 中
SessionLocaleResolver slr = new SessionLocaleResolver();
// 設(shè)置默認(rèn)語言 = 簡體中文,可以用 Locale.CHINA
slr.setDefaultLocale(Constants.DEFAULT_LOCALE);
return slr;
}
?
/**
* LocaleChangeInterceptor: Spring 提供的用于切換 Locale 的攔截器,攔截 HTTP 請求中的參數(shù)來確定用戶想要切換到的語言
* lci.setParamName("lang"): 設(shè)置 URL 請求中的參數(shù)名為 lang
* 即用戶可以通過傳遞 ?lang=xx 來切換語言(如 ?lang=zh_CN 切換到簡體中文,?lang=en 切換到英文)
* @return
*/
@Bean
public LocaleChangeInterceptor localeChangeInterceptor()
{
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 參數(shù)名
lci.setParamName("lang");
return lci;
}
?
/**
* WebMvcConfigurer 添加自定義攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry)
{
// 添加攔截器
registry.addInterceptor(localeChangeInterceptor());
}
}4 封裝消息工具
package com.okyun.common.utils;
?
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import com.okyun.common.utils.spring.SpringUtils;
?
/**
* 獲取i18n資源文件
*
* @author hubiao
*/
public class MessageUtils
{
/**
* 根據(jù)消息鍵和參數(shù) 獲取消息 委托給spring messageSource
*
* @param code 消息鍵
* @param args 參數(shù)
* @return 獲取國際化翻譯值
*/
public static String message(String code, Object... args)
{
// MessageSource:Spring 的國際化資源接口,主要用于獲取不同語言環(huán)境下的消息內(nèi)容
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
// LocaleContextHolder.getLocale():從 LocaleContextHolder 中獲取當(dāng)前線程的 Locale(語言環(huán)境)
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}
5 后臺業(yè)務(wù)中使用
AjaxResult.error(MessageUtils.message("user.password.retry.limit.exceed",new Object[] { retryLimitCount, lockTime }))
6 前端切換語言
/**
* 切換語言
* @param lang
* @return
*/
@GetMapping("/changeLanguage")
public AjaxResult changeLanguage(String lang)
{
return AjaxResult.success();
}
7 特殊國際化處理 - 參數(shù)校驗注解
/**
* 參數(shù)驗證國際化
*/
@Size(max = 30, message = "編碼最大長度30個字符")
@Pattern(regexp = "^[^+-].*", message = "編碼不能以 + 或 - 開頭")
private String productNo;
// 舉例 @Size(max = 30, message = "size.max.valid")
# Spring 會自動從 `messages.properties` 加載對應(yīng)的消息
size.between.valid=長度必須在{min}到{max}個字符之間
size.max.valid=長度不能超過{max}個字符
size.min.valid=長度不能少于{min}個字符
8 特殊國際化處理 - Excel列名
8.1 Excel注解添加i18n字段
package com.okyun.common.annotation;
/**
* 自定義導(dǎo)出Excel數(shù)據(jù)注解
*
* @author hubiao
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel{
...
/**
* 國際化Key(優(yōu)先級高于name).
* 示例: excel.user.name
*/
public String i18nKey() default "";
...
}
8.2 ExcelUtil 方法添加獲取國際化邏輯
package com.okyun.common.utils.poi;
/**
* Excel相關(guān)處理
* @author hubiao
*/
public class ExcelUtil<T>{
...
// 國際化 - 注入MessageSource(若依中可通過SpringUtils獲取)
private static final MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
/**
* 獲取國際化表頭名稱
*/
private String getI18nHeader(Excel excelAttr) {
if (StringUtils.isNotEmpty(excelAttr.i18nKey())) {
return messageSource.getMessage(
excelAttr.i18nKey(),
null,
LocaleContextHolder.getLocale()
);
}
return excelAttr.name(); // 默認(rèn)返回name
}
/**
* 創(chuàng)建單元格
*/
public Cell createHeadCell(Excel attr, Row row, int column){
...
// 寫入列信息 - 國際化
cell.setCellValue(getI18nHeader(attr));
...
}
/**
* 添加單元格
*/
public Cell addCell(Excel attr, Row row, T vo, Field field, int column){
......
else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) {
String label = DictUtils.getDictLabel(
dictType,
Convert.toStr(value),
separator,
LocaleContextHolder.getLocale() // 傳遞當(dāng)前語言環(huán)境
);
cell.setCellValue(label);
}
......
}
...
}
8.3 字典數(shù)據(jù)國際化
package com.okyun.common.utils;
/**
* 字典工具類
*
* @author hubiao
*/
public class DictUtils{
......
/**
* 獲取國際化字典標(biāo)簽(完整實現(xiàn))
* @param dictType 字典類型
* @param dictValue 字典值
* @param separator 分隔符
* @param locale 語言環(huán)境
* @return 字典標(biāo)簽
*/
public static String getDictLabel(String dictType, String dictValue, String separator, Locale locale) {
// 1. 嘗試獲取國際化標(biāo)簽
String i18nKey = "dict." + dictType + "." + dictValue;
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
String i18nLabel = messageSource.getMessage(i18nKey, null, null, locale);
// 2. 如果不存在國際化配置,回退到系統(tǒng)字典
if (i18nLabel == null || i18nKey.equals(i18nLabel)) {
return getDictLabel(dictType, dictValue, separator); // 調(diào)用原有方法
}
return i18nLabel;
}
......
}
8.4 項目實戰(zhàn)中使用
8.4.1 @Excel注解
/** * 商品狀態(tài) * dictType 字典類型 * i18nKey 映射的字段名 */ @Excel(name = "商品狀態(tài)", dictType = "product_status", i18nKey = "product.product.status") private Integer productStatus; /** * 編碼 * i18nKey 映射的字段名 */ @Excel(name = "編碼", i18nKey = "product.product.code") private String productNo;
8.4.2 維護(hù)映射文件
# excel導(dǎo)出/導(dǎo)入 - 字段名映射 product.product.code=商品編碼 product.product.status=商品狀態(tài) # dictData 的 value 對應(yīng) label # dict 固定前綴 # dictType 字典類型 # 0 字典值 # 啟售 字典label dict.product_status.0=啟售 dict.product_status.1=停售
到此這篇關(guān)于SpringBoot3項目實現(xiàn)國際化的示例詳解的文章就介紹到這了,更多相關(guān)SpringBoot3國際化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot集成EasyExcel實現(xiàn)百萬級別的數(shù)據(jù)導(dǎo)入導(dǎo)出實踐指南
本文將基于開源項目 springboot-easyexcel-batch 進(jìn)行解析與擴(kuò)展,手把手教大家如何在 Spring Boot 2.2.1 中集成 Alibaba EasyExcel,輕松實現(xiàn)百萬級數(shù)據(jù)的導(dǎo)入與導(dǎo)出2025-08-08
springboot 在xml里讀取yml的配置信息的示例代碼
這篇文章主要介紹了springboot 在xml里讀取yml的配置信息的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
java Map轉(zhuǎn)Object與Object轉(zhuǎn)Map實現(xiàn)代碼
這篇文章主要介紹了 java Map轉(zhuǎn)Object與Object轉(zhuǎn)Map實現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-02-02
RestTemplate設(shè)置超時時間及返回狀態(tài)碼非200處理
這篇文章主要為大家介紹了RestTemplate設(shè)置超時時間及返回狀態(tài)碼非200處理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

