Spring核心——MessageSource实现国际化
为什么80%的码农都做不了架构师?>>>
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(String[] args) {//使用当前操作系统的语言环境ResourceBundle rb = ResourceBundle.getBundle("i18n", Locale.getDefault());System.out.println(rb.getString("say"));//指定简体中文环境rb = ResourceBundle.getBundle("i18n", new Locale("zh", "CN"));System.out.println(rb.getString("say"));//通过预设指定简体英文环境rb = ResourceBundle.getBundle("i18n", Locale.SIMPLIFIED_CHINESE);System.out.println(rb.getString("say"));//指定美国英语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("say"));}
}
按照开发文档的要求,使用ResourceBundle加载的资源文件都必须放置在根目录,并且必须按照${name}_${language}_${region}的方式来命名。这个命名方式正好能对应ResourceBundle::getBundle方法中的参数,例如ResourceBundle.getBundle("i18n", new Locale("zh", "CN"))。"i18n"对应${name},"zh"定位${language},而“CN”对应${region}。这样我们就可以通过传导参数来使用不同的资源。如果不指定${language}和${region},该文件就是一个默认文件。
Locale类预设了很多资源类型,比如Locale.SIMPLIFIED_CHINESE、Locale.US,实际上他们就等价于new Locale("zh", "CN")和new Locale("en", "US")。只是Java的开发人员做了一些静态的预设。
除了预设内容的Locale,我们还可以像Locale locale = new Locale("web", "BASE64")这样添加自定义的内容,他对应名为i18n_web_BASE64.properties的资源文件。
MessageSource的使用
MessageSource的功能就是用Java标准库的ResourceBundle实现的,所以使用起来也差不多。
首先得将用于处理国际化资源的Bean添加到IoC容器中:
@Configuration
public class I18nApp {@Bean("messageSource")ResourceBundleMessageSource resourceBundleMessageSource() {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasenames(new String[] { "i18n", "extend" });//添加资源名称return messageSource;}
}
或
<beans><bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource"><property name="basenames"><list><value>i18n</value><value>extend</value></list></property></bean>
</beans>
切记一定要标记id=messageSource。basenames这个Setter用于指定*.properties资源文件的名称,规则和前面介绍的ResourceBundle一样。然后就可以通过ApplicationContext::getMessage方法获取对应的资源了:
@Configuration
public class I18nApp {@Bean("messageSource")ResourceBundleMessageSource resourceBundleMessageSource() {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasenames(new String[] { "i18n", "extend" });return messageSource;}public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(I18nApp.class);System.out.println("Spring Default 1:" + context.getMessage("say", null, Locale.getDefault()));System.out.println("Spring Default 2:" + context.getMessage("say", null, null));System.out.println("Spring Chinese:" + context.getMessage("say", null, Locale.SIMPLIFIED_CHINESE));System.out.println("Spring Us English:" + context.getMessage("say", null, Locale.US));System.out.println("Spring Custom:" + context.getMessage("say", null, new Locale("web", "BASE64")));System.out.println("Spring Argument:" + context.getMessage("info", new String[] {"chkui"},null));System.out.println("Spring Info:" + context.getMessage("say", null, null));}
}
占位符替换
注意上面的示例代码的这一行:context.getMessage("info", new String[] {"chkui"},null)),这里的getMessage向方法传递了一个数组,他用于替换资源文件中的占位符号。在例子中我们除了i18n还加载了一个extend.properties文件,文件内容如下:
info={0}\u5E05\u7684\u8BA9\u4EBA\u6CA1\u813E\u6C14\u3002
文件中的{0}表示这个位置用数组中的[0]位置的元素替换。
还有一点需要注意的是,*.properties文件输入中文等UTF-8的符号时需要保留上面这种ACS的格式,现在大部分IDE都会自动处理的,切记不要为了方便看内容将*.properties的编码格式切换为UTF-8。
获取MessageSource接口
我们有三种方式获取MessageSource接口:
//直接使用
ApplicationContext context = new AnnotationConfigApplicationContext(I18nApp.class);
context.getMessage("say", null, Locale.getDefault()));//MessageSourceAware(ApplicationContextAware)接口
public class ExtendBean implements MessageSourceAware {@Overridepublic void setMessageSource(MessageSource messageSource) {this.setterMs = messageSource;}
}//从容器直接注入
public class ExtendBean implements MessageSourceAware {@Autowiredprivate MessageSource autowiredMs;
}
需要注意的是,使用@Autowired等方式直接获取MessageSource类型的数据得到的是添加到容器的那个Bean,而其他方式获取到的是ApplicationContext。
转载于:https://my.oschina.net/chkui/blog/1923011
Spring核心——MessageSource实现国际化相关推荐
- 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程)
相关内容: 架构师系列内容:架构师学习笔记(持续更新) 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程) 一步一步手绘Spring IOC运行时序图二(基于XM ...
- Spring核心编程思想
第01章:Spring Framework总览 (12讲) 01.课程介绍.mp4 02.内容综述.mp4 03.课前准备:学习三件套(工具.代码与大脑).mp4 ...
- Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(二)
前言 registerBeanPostProcessors initMessageSource 如何实际应用国际化处理 initApplicationEventMulticaster onRefres ...
- 小马哥spring编程核心思想_极客小马哥Spring核心编程思想
42 | 依赖查找的今世前生:Spring IoC容器从Java标准中学到了什么? 43 | 单一类型依赖查找:如何查找已知名称或类型的Bean对象? 44 | 集合类型依赖查找:如何查找已知类型多个 ...
- Spring MVC-08循序渐进之国际化(基于Session-SessionLocaleResolver)
概述 工程结构 测试 源码 概述 在Spring MVC中选择语言区域,可以使用语言解析器Bean,它包括几个实现,如下 AcceptHeaderLocaleResolver SessionLocal ...
- Spring教程 - Spring核心框架教程
Spring教程 - Spring核心框架教程 Spring是最广泛使用的Java EE框架之一.我已经在Spring Tutorial上写了很多内容,这是一篇摘要文章,它将作为索引按顺序完成所有这些 ...
- SSM Chapter 05 Spring 核心概念
SSM Chapter 05 Spring 核心概念 笔记 本章目标: 理解Spring IoC的原理 掌握Spring IoC的配置 理解Spring AOP的原理 掌握Spring AOP的配置 ...
- Spring 核心方法 refresh 刷新流程简要概述及相关源码扩展实现(一)
前言 Spring 启动流程解析 Refresh 内部方法全解析 prepareRefresh obtainFreshBeanFactory AbstractApplicationContext 类以 ...
- 05. 手写Spring核心框架
目录 05 手写Spring核心框架 Pt1 手写IoC/DI Pt1.1 流程设计 Pt1.2 基础配置 application.properties pom.xml web.xml Pt1.3 注 ...
- Spring Boot Validation提示信息国际化配置
引言 之前介绍过Spring Boot Validation的使用及扩展,可参见:<SpringBoot Validation> 本文在此基础上重点讲解下Spring Boot Valid ...
最新文章
- RGB+Depth规则箱体测量方案
- [武道资料]《菲律宾短棍-单棍》(Edgar Sulite Lameco Escrima Single Stick)
- mysql打开网络访问权限_远程连接mysql 授权方法详解
- java服务器和linux_在Linux下开一个Java服务器(使用CatServer Pro)
- c语言中math的库函数,C语言中math.h库中的常用函数
- 双11首日全国共揽收快递包裹5.69亿件 同比增长28.54%
- MySQL集群架构:MHA+MySQL-PROXY+LVS实现MySQL集群架构高可用/高性能-技术流ken
- 218.94.78.76:20001/index.php,详解spring中使用Elasticsearch的实例教程
- 【OpenCV新手教程之十三】OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放...
- 【大数据部落】基于随机森林、svm、CNN机器学习的风控欺诈识别模型
- 【Visual Assist X】VAssistX的安装和使用
- 输入一行数字、数字之间用空格隔开python_Python 实现一行输入多个数字(用空格隔开)...
- 什么是运维高手的境界?
- shc加密shell脚本
- Talk预告 | 中国科学技术大学和微软亚洲研究院联合培养博士生冷燚冲:语音识别的快速纠错模型FastCorrect
- 大话C语言——优化结构控制(一)
- pod init 报错 can‘t modify frozen String (FrozenError) [Xcodeproj] Unknown object version (56).
- linux 输出到文件 新,如何将Linux命令输出保存到文件的两种方法
- 泛微Ecology8.0浏览框详解
- 双十一马上到来了,程序员都在干什么呢?程序员:我太难了…