你好,我是看山。
咱们今天一起来聊聊 SpringBoot 中的国际化组件 MessageSource。
先看一下类图:
从类图可以看到,Spring 内置的MessageSource
有三个实现类:
在 SpringBoot 中,默认创建 ResourceBundleMessageSource 实例实现国际化输出。标准的配置通过MessageSourceProperties
类注入:
MessageFormat.format
函数对国际化信息格式化,如果注入参数,输出结果是经过格式化的。比如MessageFormat.format("Hello, {0}!", "Kanshan")
输出结果是“Hello, Kanshan!”。该参数控制的是,当输入参数为空时,是否还是使用MessageFormat.format
函数对结果进行格式化,默认是 false;NoSuchMessageException
异常。从上面我们知道了一些简单的配置,但是还是没有办法知道 MessageSource 到底是什么,本节我们举个例子小试牛刀。
首先从https://start.spring.io/创建一个最少依赖spring-boot-starter-web
的 SpringBoot 项目。
然后在 resources 目录下定义一组国际化配置文件,我们这里使用默认配置,所以 basename 是 messages:
## messages.properties
message.code1=[DEFAULT]code one
message.code2=[DEFAULT]code two
message.code3=[DEFAULT]code three
message.code4=[DEFAULT]code four
message.code5=[DEFAULT]code five
message.code6=[DEFAULT]code six## messages_en.properties
message.code2=[en]code two## messages_en_US.properties
message.code3=[en_US]code three## messages_zh.properties
message.code4=[中文] 丁字号## messages_zh_CN.properties
message.code5=[大陆区域中文] 戊字号## messages_zh_Hans.properties
message.code6=[简体中文] 己字号
一个定义了六个配置文件:
从上面配置文件的命名可以看出,都是以 basename 开头,后面跟上语系和地区,三个参数以下划线分隔。
可以支持的语言和国家可以从java.util.Locale
查找。
最后我们定义一个 Controller 实验:
@RestController
public class HelloController {&#64;Autowiredprivate MessageSource messageSource;&#64;GetMapping("m1")public List<String> m1(Locale locale) {final List<String> multi &#61; new ArrayList<>();multi.add(messageSource.getMessage("message.code1", null, locale));multi.add(messageSource.getMessage("message.code2", null, locale));multi.add(messageSource.getMessage("message.code3", null, locale));multi.add(messageSource.getMessage("message.code4", null, locale));multi.add(messageSource.getMessage("message.code5", null, locale));multi.add(messageSource.getMessage("message.code6", null, locale));return multi;}
}
我们通过不同的请求查看结果&#xff1a;
### 默认
GET http://localhost:8080/m1
### 结果是&#xff1a;
["[DEFAULT]code one","[DEFAULT]code two","[DEFAULT]code three","[中文] 丁字号","[大陆区域中文] 戊字号","[简体中文] 己字号"
]### local: en
GET http://localhost:8080/m1
Accept-Language: en
### 结果是&#xff1a;
["[DEFAULT]code one","[en]code two","[DEFAULT]code three","[DEFAULT]code four","[DEFAULT]code five","[DEFAULT]code six"
]### local: en-US
GET http://localhost:8080/m1
Accept-Language: en-US
### 结果是&#xff1a;
["[DEFAULT]code one","[en]code two","[en_US]code three","[DEFAULT]code four","[DEFAULT]code five","[DEFAULT]code six"
]### local: zh
GET http://localhost:8080/m1
Accept-Language: zh
### 结果是&#xff1a;
["[DEFAULT]code one","[DEFAULT]code two","[DEFAULT]code three","[中文] 丁字号","[DEFAULT]code five","[DEFAULT]code six"
]### local: zh-CN
GET http://localhost:8080/m1
Accept-Language: zh-CN
### 结果是&#xff1a;
["[DEFAULT]code one","[DEFAULT]code two","[DEFAULT]code three","[中文] 丁字号","[大陆区域中文] 戊字号","[DEFAULT]code six"
]
从上面的结果可以看出&#xff1a;
zh-Hans
&#xff0c;所以结果是简体中文优先&#xff1b;我们在 message.properties 中添加一行配置&#xff1a;
message.multiVars&#61;var1&#61;{0}, var2&#61;{1}
在刚才的 Controller 中增加一个请求&#xff1a;
&#64;GetMapping("m2")
public List<String> m2(Locale locale) {final List<String> multi &#61; new ArrayList<>();multi.add("参数为 null: " &#43; messageSource.getMessage("message.multiVars", null, locale));multi.add("参数为空&#xff1a;" &#43; messageSource.getMessage("message.multiVars", new Object[]{}, locale));multi.add("只传一个参数&#xff1a;" &#43; messageSource.getMessage("message.multiVars", new Object[]{"第一个参数"}, locale));multi.add("传两个参数&#xff1a;" &#43; messageSource.getMessage("message.multiVars", new Object[]{"第一个参数", "第二个参数"}, locale));multi.add("传超过两个参数&#xff1a;" &#43; messageSource.getMessage("message.multiVars", new Object[]{"第一个参数", "第二个参数", "第三个参数"}, locale));return multi;
}
我们看看结果&#xff1a;
###
GET http://localhost:8080/m2
### 结果是&#xff1a;
["参数为 null: var1&#61;{0}, var2&#61;{1}","参数为空&#xff1a;var1&#61;{0}, var2&#61;{1}","只传一个参数&#xff1a;var1&#61;第一个参数&#xff0c;var2&#61;{1}","传两个参数&#xff1a;var1&#61;第一个参数&#xff0c;var2&#61;第二个参数","传超过两个参数&#xff1a;var1&#61;第一个参数&#xff0c;var2&#61;第二个参数"
]
我们可以看到&#xff0c;我们在配置文件中定义了带参数的配置信息&#xff0c;此时&#xff0c;我们可以不传参数、传少于指定数量的参数、传符合指定数量的参数、传超过指定数量的参数&#xff0c;都可以正常返回国际化信息。
此处可以理解为&#xff0c;MessageFormat.format
执行过程是for-index
循环&#xff0c;从配置值中找格式为{数字}
的占位符&#xff0c;然后用对应下标的输入参数替换&#xff0c;如果属于参数没了&#xff0c;就保持原样。
如果我们的配置文件中没有配置或者对应语言及其父级都没有配置呢&#xff1f;
这个就要靠前面说的useCodeAsDefaultMessage
配置了&#xff0c;如果为 true&#xff0c;就会返回输入的 code&#xff0c;如果为 false&#xff0c;就会抛出异常。默认是 false&#xff0c;所以如果找不到会抛异常。比如&#xff1a;
&#64;GetMapping("m3")
public List<String> m3(Locale locale) {final List<String> multi &#61; new ArrayList<>();multi.add("不存在的 code: " &#43; messageSource.getMessage("message.notExist", null, locale));return multi;
}
这个时候我们执行 http 请求&#xff1a;
###
GET http://localhost:8080/m3
### 结果是&#xff1a;
{"timestamp": "2022-06-19T09:14:14.977&#43;00:00","status": 500,"error": "Internal Server Error","path": "/m3"
}
这是报错了&#xff0c;异常栈是&#xff1a;
org.springframework.context.NoSuchMessageException: No message found under code &#39;message.notExist&#39; for locale &#39;zh_CN_#Hans&#39;.at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:161) ~[spring-context-5.3.20.jar:5.3.20]at cn.howardliu.effective.spring.springbootmessages.controller.HelloController.m3(HelloController.java:47) ~[classes/:na]……此处省略
本文开头说过&#xff0c;MessageSource 有三种实现&#xff0c;Spring 默认使用了 ResourceBundleMessageSource&#xff0c;我们可以自定义使用 ReloadableResourceBundleMessageSource。
既然是在 SpringBoot 中&#xff0c;我们可以依靠 SpringBoot 的特性定义&#xff1a;
&#64;Configuration(proxyBeanMethods &#61; false)
&#64;ConditionalOnMissingBean(name &#61; AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search &#61; SearchStrategy.CURRENT)
&#64;ConditionalOnProperty(name &#61; "spring.messages-type", havingValue &#61; "ReloadableResourceBundleMessageSource")
&#64;AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
&#64;Conditional(ReloadResourceBundleCondition.class)
&#64;EnableConfigurationProperties
public class ReloadMessageSourceAutoConfiguration {private static final Resource[] NO_RESOURCES &#61; {};&#64;Bean&#64;ConfigurationProperties(prefix &#61; "spring.messages")public MessageSourceProperties messageSourceProperties() {return new MessageSourceProperties();}&#64;Beanpublic MessageSource messageSource(MessageSourceProperties properties) {ReloadableResourceBundleMessageSource messageSource &#61; new ReloadableResourceBundleMessageSource();if (StringUtils.hasText(properties.getBasename())) {final String[] originBaseNames &#61; StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()));final String[] baseNames &#61; new String[originBaseNames.length];for (int i &#61; 0; i < originBaseNames.length; i&#43;&#43;) {if (originBaseNames[i].startsWith("classpath:")) {baseNames[i] &#61; originBaseNames[i];} else {baseNames[i] &#61; "classpath:" &#43; originBaseNames[i];}}messageSource.setBasenames(baseNames);}if (properties.getEncoding() !&#61; null) {messageSource.setDefaultEncoding(properties.getEncoding().name());}messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());Duration cacheDuration &#61; properties.getCacheDuration();if (cacheDuration !&#61; null) {messageSource.setCacheMillis(cacheDuration.toMillis());}messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());return messageSource;}protected static class ReloadResourceBundleCondition extends SpringBootCondition {private static final ConcurrentReferenceHashMap<String, ConditionOutcome> CACHE &#61;new ConcurrentReferenceHashMap<>();&#64;Overridepublic ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {String basename &#61; context.getEnvironment().getProperty("spring.messages.basename", "messages");ConditionOutcome outcome &#61; CACHE.get(basename);if (outcome &#61;&#61; null) {outcome &#61; getMatchOutcomeForBasename(context, basename);CACHE.put(basename, outcome);}return outcome;}private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {ConditionMessage.Builder message &#61; ConditionMessage.forCondition("ResourceBundle");for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {for (Resource resource : getResources(context.getClassLoader(), name)) {if (resource.exists()) {return ConditionOutcome.match(message.found("bundle").items(resource));}}}return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " &#43; basename).atAll());}private Resource[] getResources(ClassLoader classLoader, String name) {String target &#61; name.replace(&#39;.&#39;, &#39;/&#39;);try {return new PathMatchingResourcePatternResolver(classLoader).getResources("classpath*:" &#43; target &#43; ".properties");} catch (Exception ex) {return NO_RESOURCES;}}}}
我们可以看到&#xff0c;我们在执行messageSource.setBasenames(baseNames);
的时候&#xff0c;baseNames
中的值都是设置成classpath:
开头的&#xff0c;这是为了使ReloadableResourceBundleMessageSource
能够读取 CLASSPATH 下的配置文件。当然也可以使用绝对路径或者相对路径实现&#xff0c;这个是比较灵活的。
我们可以通过修改配置文件内容&#xff0c;查看变化&#xff0c;这里就不再赘述。纸上得来终觉浅&#xff0c;绝知此事要躬行。
本文通过几个小例子介绍了MessageSource
的使用。这里做一下预告&#xff0c;下一章我们会从源码角度分析MessageSourc
e 的实现类ResourceBundleMessageSource
和ReloadableResourceBundleMessageSource
的执行逻辑&#xff1b;然后我们自定义扩展&#xff0c;从 Nacos 中读取配置内容&#xff0c;实现更加灵活的配置。
本文中的实例已经传到 GitHub&#xff0c;关注公众号「看山的小屋」&#xff0c;回复spring
获取源码。
青山不改&#xff0c;绿水长流&#xff0c;我们下次见。
你好&#xff0c;我是看山。游于码界&#xff0c;戏享人生。如果文章对您有帮助&#xff0c;请点赞、收藏、关注。我还整理了一些精品学习资料&#xff0c;关注公众号「看山的小屋」&#xff0c;回复“资料”即可获得。
个人主页&#xff1a;https://www.howardliu.cn
个人博文&#xff1a;《SpringBoot 手册》&#xff1a;国际化组件 MessageSource
CSDN 主页&#xff1a;https://kanshan.blog.csdn.net/
CSDN 博文&#xff1a;《SpringBoot 手册》&#xff1a;国际化组件 MessageSource