代碼邏輯示例
{
// 遍歷循環(huán)配置文件basename集合.
for (String baseName : Arrays.asList("spring.messages.basename")){
/**
* 根據(jù) locale 遍歷父級(jí)的locale對(duì)象,
* {@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)}
* 當(dāng)父級(jí)遍歷完畢, 設(shè)置當(dāng)前l(fā)ocale對(duì)象為系統(tǒng)默認(rèn)locale對(duì)象.
* {@link ResourceBundleMessageSource#resolveCodeWithoutArguments(java.lang.String, java.util.Locale)}
*/
for (String locale : Arrays.asList("locale", "parentLocale", "defaultLocale", "defaultParentLocale")) {
// 如果當(dāng)前keySet集合存在該元素則返回對(duì)應(yīng)數(shù)據(jù)并結(jié)束遍歷.
if (ResourceBundle.getBundle(baseName, Locale.forLanguageTag(locale)).keySet().contains("目標(biāo)讀取key")) {
return ResourceBundle.getBundle(baseName, Locale.forLanguageTag(locale)).getString("目標(biāo)讀取key");
}
}
}
return "默認(rèn)值";
}
效果展示
spring.messages.basename=i18n/messages,other,messages
當(dāng)前配置文件:
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
當(dāng)前baseName獲取不到對(duì)應(yīng)的bundle 則根據(jù)默認(rèn)的locale進(jìn)行取值.

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

浙公網(wǎng)安備 33010602011771號(hào)