欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot3項(xiàng)目實(shí)現(xiàn)國際化的示例詳解

 更新時(shí)間:2025年08月13日 09:08:28   作者:xiguolangzi  
這篇文章主要為大家詳細(xì)介紹了SpringBoot3如何在項(xiàng)目中實(shí)現(xiàn)國際化的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

下面小編就來和大家簡單介紹一下springBoot3 項(xiàng)目實(shí)現(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=密碼輸入錯(cuò)誤{0}次,帳戶鎖定{1}分鐘

2 配置 application.yml

  # Spring配置
  spring:
    # 資源信息
    messages:
      # 國際化資源文件路徑,如果有多個(gè)通過逗號(hào)隔開,這里的messages不是路徑,而是文件名前綴
      basename: i18n/messages
      encoding: UTF-8

3 維護(hù) i8n 配置類

  package com.okyun.framework.config;
  ?
  /**
   * 資源文件配置加載
   * 語言切換優(yōu)先級(jí) -> 1 請(qǐng)求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 用來解析和存儲(chǔ)用戶的 Locale 信息在會(huì)話 (session) 中
          SessionLocaleResolver slr = new SessionLocaleResolver();
          // 設(shè)置默認(rèn)語言 = 簡體中文,可以用 Locale.CHINA
          slr.setDefaultLocale(Constants.DEFAULT_LOCALE);
          return slr;
      }
  ?
      /**
       * LocaleChangeInterceptor: Spring 提供的用于切換 Locale 的攔截器,攔截 HTTP 請(qǐng)求中的參數(shù)來確定用戶想要切換到的語言
       * lci.setParamName("lang"): 設(shè)置 URL 請(qǐng)求中的參數(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 后臺(tái)業(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ù)校驗(yàn)注解

/**
* 參數(shù)驗(yàn)證國際化
*/
@Size(max = 30, message = "編碼最大長度30個(gè)字符")
@Pattern(regexp = "^[^+-].*", message = "編碼不能以 + 或 - 開頭")
private String productNo;

// 舉例 @Size(max = 30, message = "size.max.valid")
# Spring 會(huì)自動(dòng)從 `messages.properties` 加載對(duì)應(yīng)的消息
size.between.valid=長度必須在{min}到{max}個(gè)字符之間
size.max.valid=長度不能超過{max}個(gè)字符
size.min.valid=長度不能少于{min}個(gè)字符

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)先級(jí)高于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)簽(完整實(shí)現(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 項(xiàng)目實(shí)戰(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 對(duì)應(yīng) label
# dict 固定前綴
# dictType 字典類型
# 0 字典值
# 啟售 字典label
dict.product_status.0=啟售
dict.product_status.1=停售

到此這篇關(guān)于SpringBoot3項(xiàng)目實(shí)現(xiàn)國際化的示例詳解的文章就介紹到這了,更多相關(guān)SpringBoot3國際化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論