Spring的ApplicationContext容器的国际化支持
Spring的ApplicationContext容器是支持国际化的,可以通过本地的默认语言显示对应语言的内容。当然这是依赖于资源文件的。
一、国际化资源文件内容
文件名message_en_US.properties(美式英语)
hello=welcome,{0}
now=now is {0}
文件名message_zh_CN.properties(中文)
hello=欢迎,{0}
now=现在的时间是:{0}
二、bean.xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!--spring调用messageSource Bean的setBasenames方法-->
<property name="basenames">
<!--可配置多个国际化资源文件-->
<list>
//加入message资源文件
<value>message</value>
</list>
</property>
</bean>
</beans>
三、现在可以在测试类中进行测试
public class BeanTest {
private ApplicationContext ctx;
@Before
public void before(){
ctx=new ClassPathXmlApplicationContext("beans.xml"); //实例化ApplicationContext容器指定使用的bean文件
}
@Test
public void messageTest(){ //spring国际化测试
//getMessage用于获取本地化消息,而其中的Locale.getDefault()方法返回的是本地计算机默认的Locale
String hello=ctx.getMessage("hello",new String[]{"张三"}, Locale.getDefault(Locale.Category.FORMAT));
String now=ctx.getMessage("now",new Date[]{new Date()}, Locale.getDefault(Locale.Category.FORMAT));
System.out.println(hello); //在控制台输出hello的内容
System.out.println(now); //在控制台输出now的内容
}
}
然后运行测试就ok啦。