新建两个国际化资源文件
resource_en_US.properties
resource_zh_CN.properties
格式:资源文件的名称_<语言>_<国家>.properties
resource_en_US.properties
name=I am {0},today is {1} year!
resource_zh_CN.properties
name=\u6211\u53EB{0},\u4ECA\u5929{1}\u5E74!
配置applicationContext.xml
<bean id="resource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>resource</value>
</list>
</property>
<property name="cacheSeconds" value="5"></property>
</bean>
测试类:
package com.ioc;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.ResourceBundleMessageSource;
public class ResourceUtil {
public static void main(String[] args) {
//时间格式化
String datestring = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss").format(new Date());
System.out.println(datestring);
//数字格式化
String num = new DecimalFormat("0.000").format(12.34534);
System.out.println(num);
//JDK自带的国际化
//统一使用一个资源文件进行管理.
//名称必须:资源文件的名称_<语言>_<国家>.properties
//如资源文件不在classpath,ResourceBundle.getBundle("com/ioc/resource",Locale.CHINA);
ResourceBundle resourceBundle = ResourceBundle.getBundle("resource",Locale.US);
ResourceBundle resourceBundle1 = ResourceBundle.getBundle("resource",Locale.CHINA);
Object[] params = {"MM",2016};
String str1 = new MessageFormat(resourceBundle.getString("name")).format(params);
String str2 = new MessageFormat(resourceBundle1.getString("name")).format(params);
System.out.println(str1);
System.out.println(str2);
//spring 国际化
//加载资源文件---获取资源文件中的内容----替换数据
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
ResourceBundleMessageSource resourceBundleMessageSource = (ResourceBundleMessageSource) context.getBean("resource");
String str3 = resourceBundleMessageSource.getMessage("name", params, Locale.US);
String str4 = resourceBundleMessageSource.getMessage("name", params, Locale.CHINA);
System.out.println(str3);
System.out.println(str4);
}
}
2016-12-16 15:29:07:007
12.345
I am MM,today is 2,016 year!
我叫MM,今天2,016年!
十二月 16, 2016 3:29:07 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6477463f: startup date [Fri Dec 16 15:29:07 CST 2016]; root of context hierarchy
十二月 16, 2016 3:29:07 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
十二月 16, 2016 3:29:08 下午 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [jdbc.properties]
I am MM,today is 2,016 year!
我叫MM,今天2,016年!