发表于: 2022-06-21 20:25:40

1 244



Spring的国际化

上下文与IoC对ApplicationContext以及Context相关的设计模式进行了介绍。

ApplicationContext作为一个Context在应用的运行层提供了IoC容器、事件、国际化等功能接口。

Spring的国际化(i18n)功能是通过MessageSource接口实现的,他提供了MessageSource::getMessage方法从预设的资源中获取对应的数据。

Java标准资源绑定

在介绍MessageSource之前,得先说清楚Java(J2SE)对国际化的基本实现——ResourceBundle,因为MessageSource是用它实现的。

ResourceBundle很好理解,他就是按照规范的格式放置*.properties资源文件,然后根据输入的语言环境来返回资源。



用Spring messageSource 配置错误信息:


有3个资源文件放置在classpath的根目录中,文件名分别为i18n_en_US.propertiesi18n_zh_CN.propertiesi18n_web_BASE64.properties。

i18n_en_US.properties:

#i18n_en_US.properties
say=Hallo world!

i18n_zh_CN.properties:

#i18n_zh_CN.properties
#该字段含义是  大家好!
-1=\u5927\u5BB6\u597D\uFF01

i18n_web_BASE64.properties:

#i18n_web_BASE64.properties
say=+-+-+-ABC


MessageSource的使用

MessageSource的功能就是用Java标准库的ResourceBundle实现的,所以使用起来也差不多。

创建配置I18App文件:



@Configuration
public class I18nApp {

//将用于处理国际化资源的Bean添加到IoC容器中

   @Bean("messageSource")

ResourceBundleMessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
       messageSource.setBasenames(new String[] { "i18n", "extend" });//添加资源名称
       return messageSource;

   }


public static void main(String[] args) {

//使用当前操作系统的语言环境
           ResourceBundle rb = ResourceBundle.getBundle("i18n", Locale.getDefault());
           System.out.println(rb.getString("-1"));

           //指定简体中文环境
           rb = ResourceBundle.getBundle("i18n", new Locale("zh", "CN"));
           System.out.println(rb.getString("-1"));
           //通过预设指定简体英文环境
           rb = ResourceBundle.getBundle("i18n", Locale.SIMPLIFIED_CHINESE);
           System.out.println(rb.getString("-1"));

           //指定美国英语
           rb = ResourceBundle.getBundle("i18n", Locale.US);
           System.out.println(rb.getString("say"));

           //使用自定义的语言环境
           Locale locale = new Locale("web", "BASE64");
           rb = ResourceBundle.getBundle("i18n", locale);
           System.out.println(rb.getString("0"));
       }
}




返回对应的错误信息:





收获:以上




明天计划:完成接下来的任务







返回列表 返回列表
评论

    分享到