Spring Applicationcontext的国际化支持

本文介绍如何在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>

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

测试代码:

publicstaticvoidmain(String[]args)throwsException...{

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}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值