核心思路:将程序中需要实现国际化的信息写入资源文件,代码中仅仅使用相应的个信息的key。
上代码!
首先建立两个文件,一个中文,一个英文。
message_en_US.properties
hello=welcome,{0}
now=now is :{0}
message_zh_CN.properties
hello=欢迎你,{0}
now=现在的时间是:{0}
beans.xml文件
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message</value>
</list>
</property>
</bean>
建立一个测试类
package com.test;
import java.util.Date;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test02 {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
String hello = ctx.getMessage("hello", new String []{"猴子"},
Locale.getDefault(Locale.Category.FORMAT));
String now = ctx.getMessage("now",new Object[]{new Date()} ,
Locale.getDefault(Locale.Category.FORMAT));
System.out.println(hello);
System.out.println(now);
}
}
输出结果
欢迎你, 猴子
现在的时间是: 17-4-14 下午4:28
在英文环境下,输出的就是英文版的咯!