Spring的国际化
在上下文与IoC对ApplicationContext以及Context相关的设计模式进行了介绍。ApplicationContext作为一个Context在应用的运行层提供了IoC容器、事件、国际化等功能接口。
Spring的国际化(i18n)功能是通过MessageSource接口实现的,他提供了MessageSource::getMessage方法从预设的资源中获取对应的数据。
Java标准资源绑定
在介绍MessageSource之前,得先说清楚Java(J2SE)对国际化的基本实现——ResourceBundle,因为MessageSource是用它实现的。ResourceBundle很好理解,他就是按照规范的格式放置*.properties资源文件,然后根据输入的语言环境来返回资源。看一个代码例子就很容易明白了。
(可执行代码请到gitee下载,本文的示例代码在chkui.springcore.example.hybrid.i18n包中。)
我们有3个资源文件放置在classpath的根目录(本例是放在src/main/resource)中,文件名分别为i18n_en_US.properties、i18n_zh_CN.properties和i18n_web_BASE64.properties。文件中的内容如下:
#i18n_en_US.properties
say=Hallo world!
#i18n_zh_CN.properties
say=\u5927\u5BB6\u597D\uFF01
#i18n_web_BASE64.properties
say=+-+-+-ABC
然后我们通过ResourceBundle类来使用这些i18n的资源文件:
package chkui.springcore.example.hybrid.i18n;
public class I18nApp {
public static void main(