代码逻辑示例
- {
- // 遍历循环配置文件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
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |