由于ApplicationContext接口继承了MessageSource接口,因此具有国际化功能。首先需要在spring-dao.xml <beans>标签中配置以下bean信息
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message</value>
</list>
</property>
</bean>
message.properties文件内容:
hello=欢迎你,{0}和{1}
now=现在时间是:{0}
需要通过native2ascii方法将中文内容转化为unicode格式(命令行中进入到文件目录后输入):
native2ascii message.properties message_zh_CN.properties
示例代码:
package org.seckill.springTest.entity;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
import java.util.Locale;
/**
* Created by heng on 2017/2/22.
*/
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring/spring-dao.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-2-22 下午8:12
附项目结构: