代碼邏輯示例
{
// 遍歷回圈組態檔basename集合.
for (String baseName : Arrays.asList("spring.messages.basename")){
/**
* 根據 locale 遍歷父級的locale物件,
* {@link ResourceBundle.Control.CandidateListCache#createObject(sun.util.locale.BaseLocale)}
* {@link ResourceBundle.Control.CandidateListCache#getDefaultList(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}
* 當父級遍歷完畢, 設定當前locale物件為系統默認locale物件.
* {@link ResourceBundleMessageSource#resolveCodeWithoutArguments(java.lang.String, java.util.Locale)}
*/
for (String locale : Arrays.asList("locale", "parentLocale", "defaultLocale", "defaultParentLocale")) {
// 如果當前keySet集合存在該元素則回傳對應資料并結束遍歷.
if (ResourceBundle.getBundle(baseName, Locale.forLanguageTag(locale)).keySet().contains("目標讀取key")) {
return ResourceBundle.getBundle(baseName, Locale.forLanguageTag(locale)).getString("目標讀取key");
}
}
}
return "默認值";
}
效果展示
spring.messages.basename=i18n/messages,other,messages
當前組態檔:
resources/i18n/messages.properties
resources/i18n/messages_en.properties
resources/i18n/messages_ja_JP.properties
resources/i18n/messages_zh.properties
resources/i18n/messages_zh_CN.properties
resources/messages.properties
resources/messages_en.properties
resources/messages_ja_JP.properties
resources/messages_zh.properties
resources/messages_zh_CN.properties
resources/other.properties
resources/other_en.properties
resources/other_ja_JP.properties
resources/other_zh.properties
resources/other_zh_CN.properties
en-US讀取配置順序:i18n/messages_en_US.properties
en-US讀取配置順序:i18n/messages_en.properties
en-US讀取配置順序:i18n/messages_zh_CN.properties
en-US讀取配置順序:i18n/messages_zh.properties
en-US讀取配置順序:i18n/messages.properties
en-US讀取配置順序:other_en_US.properties
en-US讀取配置順序:other_en.properties
en-US讀取配置順序:other_zh_CN.properties
en-US讀取配置順序:other_zh.properties
en-US讀取配置順序:other.properties
en-US讀取配置順序:messages_en_US.properties
en-US讀取配置順序:messages_en.properties
en-US讀取配置順序:messages_zh_CN.properties
en-US讀取配置順序:messages_zh.properties
en-US讀取配置順序:messages.properties
ja讀取配置順序:i18n/messages_ja.properties
ja讀取配置順序:i18n/messages_zh_CN.properties
ja讀取配置順序:i18n/messages_zh.properties
ja讀取配置順序:i18n/messages.properties
ja讀取配置順序:other_ja.properties
ja讀取配置順序:other_zh_CN.properties
ja讀取配置順序:other_zh.properties
ja讀取配置順序:other.properties
ja讀取配置順序:messages_ja.properties
ja讀取配置順序:messages_zh_CN.properties
ja讀取配置順序:messages_zh.properties
ja讀取配置順序:messages.properties```
原始碼示例
遍歷basename源代碼: org.springframework.context.support.ResourceBundleMessageSource#resolveCodeWithoutArguments
當前baseName獲取不到對應的bundle 則根據默認的locale進行取值.

填充locale的父級locale源代碼: java.util.ResourceBundle.Control.CandidateListCache#getDefaultList

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/546029.html
標籤:Java
