通过使用MessageSource接口,应用程序可以访问Spring资源,调用信息,并保存为不同的语言种类,对于每一种想支持的语言需要维护一个跟其他语言中消息一致的消息列表.
要使用ApplicationContext为MessageSource提供的支持,必须在配置中定义一个MessageSource类型的Bean并取名为messageSource.
MessageSource接口定义的三个国际化的方法:
1)getMessage(String,Object[],Locale)
Locale的作用是告诉ResourceBundleMessageSource当前正在查看哪个配置文件
2)getMessage(String , Object[] , String Locale)
与第一个使用方式一样,第二个参数允许在应用键的消息不可用时传入一个默认值
3)getMessage(messageSourceResolvable , Locale)
实现了Ness阿哥SOurceResolvable接口的对象,可以用来替代一组键值和一组参数
在Spring配置文件中需要做如下配置:
<bean id="messageSource" class="org.springframework,context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message</value>
</list>
</property>
</bean>
message是基础名称,查找特定的Locale的消息值时,会查找由基础名称和Locale名组合而成的属性文件,例如在查找一个en_US Locale的消息时,会去查找一个名为message_en_US.properties的文件,如果不存在,会查找message_en.properties 的属性文件,若也不存在,就会加载名为message.properties的文件.
创建两个属性文件,message_en_US.properties 和 message_zh_CN.properties
message_en_US.properties 文件写入如下内容
hello = welcome,{0} now = now is :{0}message_zh_CN.properties文件写入如下内容(eclipse会自动将不是英文的文字转换为二进制)
hello = 你好,{0} now = 现在时间是 : {0}
创建测试类,进行测试
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
String[] a = {"用户"};
String hello = ctx.getMessage("hello",a, Locale.getDefault());
Object[] b = { new Date()};
String now = ctx.getMessage("now",b,Locale.getDefault());
System.out.println("\n本地化信息");
System.out.println(hello);
System.out.println(now);
hello = ctx.getMessage("hello",a,Locale.US);//参数中的hello对应属性文件中的属性名
now = ctx.getMessage("now",b,Locale.US);
System.out.println("\nEnglish message");
System.out.println(hello);
System.out.println(now);
hello = ctx.getMessage("hello",a,Locale.CHINA);
now = ctx.getMessage("now",b,Locale.CHINA);
System.out.println("\n中文信息");
System.out.println(hello);
System.out.println(now);