Spring ApplicationContext的国际化支持
ApplicationContext接口继承MessageSource接口,因此具备国际化功能。下面是MessageSource接口定义的三个国际化方法。
》String getMessage(String code, Object[] args, Locale loc)
》String getMessage(String code, Object[] args, String default, Locale loc)
》String getMessage(MessageSourceResolvable resolvable, Locale locale)
ApplicationContext正式通过这三个方法来完成国际化的,当程序创建ApplicationContext容器时,Spring自动查找在配置文件中名为 messageSource 的 Bean 实例,一旦找到这个Bean实例,上诉3个方法的调用被委托给该MessageSource Bean。如果没有改Bean,ApplicationContext会查找其父定义中的messageSource Bean;如果找到,他将作为 messageSource Bean使用。
如果无法找到 messageSource Bean.系统会创建一个空的 StaticMessageSource Bean,该Bean能接受上诉三个方法的调用。
在Spring中配置 messageSource Bean通常使用 ResourceBundleMessageSource 类。看下面的配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 7 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 8 <property name="basenames"> 9 <list> 10 <value>message</value> 11 <!-- 如果有多个资源文件,全部列在此处 --> 12 </list> 13 </property> 14 </bean> 15 </beans>
上面的配置定义了一个 messageSource Bean,该Bean实例只指定了一份国际化资源文件,其baseName 是message
给出如下两份资源文件
第一份为美式英语的资源文件,文件名 message_en_US.properties
1 hello=welcome,{0} 2 now=now is \:{0}
第二份为简体中文的资源文件,文件名 message_zh_CN.properties
1 hello=欢迎你{0} 2 now=现在时间是:{0}
因为该资源文件包含了非西欧文字,因此,应使用 native2ascii 工具将这份资源文件国际化,命令如下:
1 native2ascii -encoding UTF-8 message.properties message_zh_CN.properties
执行上面命令后将会看到系统会多出一个message_zh_CN.properties文件,该文件将作为简体中文实际的国家化资源文件。此时,程序拥有了两份资源文件,可以自适应美式英语和简体中文的环境,主程序如下部分:
1 ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml"); 2 //创建参数数组 3 String[] a ={"张三"}; 4 //使用getMessage方法获取本地化信息。Locale的getDefault方法返回计算机环境默认Locale 5 String hello = ac.getMessage("hello", a, Locale.getDefault()); 6 Object[] b = {new Date()}; 7 //使用Locale.US获取美国英语环境 8 String now = ac.getMessage("now", b, Locale.US); 9 System.out.println(hello); 10 System.out.println(now);
结果输出
1 欢迎你张三 2 now is :9/12/13 7:34 PM
Spring的国际化支持,其实是建立在Java程序国际化的基础之上。其核心思路都是将程序需要实现国际化的信息写入资源文件,而代码中仅仅使用相应的个信息的Key。
posted on 2013-09-12 19:39 Arts&Crafts 阅读(904) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构