Spring Applicationcontext的国际化支持

国际化应用程序消息
 ApplicationContext方法:
String getMessage(String code, Object[] args, String default, Locale loc)
代表一个messageSource Bean。
 ApplicationContext搜索messageSource Bean(必须实现MessageSource接口)
 例子:在classpath中定义两个资源束messages和errors
<bean id="messageSource" class="...ResourceBundleMessageSource">
<property name="basenames">
<value>messages,errors</value>
</property>
</bean>
在classpath中搜索:
messages_pt_BR.properties errors_pt_BR.properties
messages_pt.properties errors_pt.properties
messages.properties errors.properties

配置文件:

注意,id一定为messageSource


< beans >

< bean id ="messageSource" class ="org.springframework.context.support.ResourceBundleMessageSource" >
< property name ="basenames" >
< list >
< value > message </ value >
</ list >
</ property >
</ bean >
</ beans >

测试代码:

public static void main(String[]args) throws Exception ... {

Stringpath
=newTest().getClass().getResource("/").getPath();
Stringrealpath
=path.substring(1,path.length());
ApplicationContextcontext
=newFileSystemXmlApplicationContext(realpath+"/messageresource.xml");

String[]b
=...{"读者"};
Stringhello
=context.getMessage("hello",b,Locale.getDefault());
Object[]a
=...{newDate()};
Stringnow
=context.getMessage("now",a,Locale.getDefault());

System.out.println(hello);
System.out.println(now);
}

资源文件:记得要进行转码,推荐使用ResourceBundleEditor插件

message.en.propertieshello=welcome {0}
now=now is:{0}

message.zh_CN.properties
hello =欢迎 {0}
now = 现在时间是::{0}

运行结果(本机环境是中文系统)

你可能感兴趣的:(spring,bean,xml)