可以通过如下三种方式:
beanWapper
beanFactory
applicationContext
说明:
beanWapper已经不推荐使用了
beanFactory提供一种先进的管理机制来管理bean
applicationContext新增了许多的新的功能,如果国际化,获取资源,事件的传递
这里我以国际为例:
建两个properties文件用于国际化.
Yuki_en_US.proerties代码如下:
welcome.label
=
welcome {0} :time {1}
Yuki_zh_CN.proerties代码如下:
welcome.label
=
欢迎你
{0} :
时间
{1}
applicationContext.xml
配置如下:
xml 代码
- <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" abstract="false" singleton="true" lazy-init="default"
- autowire="default" dependency-check="default">
- <property name="basename">
- <value>yuki</value>
- </property>
- ean>
这里需要注意两点:第一,
id
的名字必须是
messageSource.
属性
basename
的值为
properties
文件的前缀.
java 代码
- package test.lyx;
- import java.util.Date;
- import java.util.Locale;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.FileSystemXmlApplicationContext;
- publicclass TestMain {
- publicstaticvoid main(String[] args) {
- ApplicationContext context=new FileSystemXmlApplicationContext("test/lyx/applicationContext.xml");
- Object[] obj=newObject[]{"lyx",new Date()};
- System.out.println(context.getMessage("welcome.label",obj, Locale.CHINA));
- System.out.println(context.getMessage("welcome.label",obj, Locale.US));
- }
- }
运行结果会在控制台上打出:
欢迎你
lyx :
时间
07-1-18
上午
10:38
welcome lyx :time 1/18/07 10:38 AM
注意:
Yuki_zh_CN.proerties
文件.必须通过,
native2ascii
成
UTF-8
才好用.转换后如下:
welcome.label=\u6b22\u8fce\u4f60 {0} :\u65f6\u95f4 {1}
上面我是用了国际的插件,会自动转换.