Spring支持国际化

通过使用MessageSource接口,应用程序可以访问Spring资源,调用信息,并保存为不同的语言种类,对于每一种想支持的语言需要维护一个跟其他语言中消息一致的消息列表.

要使用ApplicationContext为MessageSource提供的支持,必须在配置中定义一个MessageSource类型的Bean并取名为messageSource.

MessageSource接口定义的三个国际化的方法:

1)getMessage(String,Object[],Locale)

Locale的作用是告诉ResourceBundleMessageSource当前正在查看哪个配置文件

2)getMessage(String , Object[] , String Locale)

与第一个使用方式一样,第二个参数允许在应用键的消息不可用时传入一个默认值

3)getMessage(messageSourceResolvable , Locale)

实现了Ness阿哥SOurceResolvable接口的对象,可以用来替代一组键值和一组参数


在Spring配置文件中需要做如下配置:

<bean id="messageSource" class="org.springframework,context.support.ResourceBundleMessageSource">

           <property name="basenames">

                        <list>

                                 <value>message</value>

                        </list>

            </property>

</bean>

message是基础名称,查找特定的Locale的消息值时,会查找由基础名称和Locale名组合而成的属性文件,例如在查找一个en_US Locale的消息时,会去查找一个名为message_en_US.properties的文件,如果不存在,会查找message_en.properties 的属性文件,若也不存在,就会加载名为message.properties的文件.


创建两个属性文件,message_en_US.properties 和 message_zh_CN.properties

message_en_US.properties 文件写入如下内容

hello = welcome,{0}
now = now is :{0}
message_zh_CN.properties文件写入如下内容(eclipse会自动将不是英文的文字转换为二进制)

hello = 你好,{0}
now = 现在时间是 : {0}


创建测试类,进行测试

 public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        String[] a = {"用户"};
        String hello = ctx.getMessage("hello",a, Locale.getDefault());
        Object[] b = { new Date()};
        String now = ctx.getMessage("now",b,Locale.getDefault());
        System.out.println("\n本地化信息");
        System.out.println(hello);
        System.out.println(now);

        hello = ctx.getMessage("hello",a,Locale.US);//参数中的hello对应属性文件中的属性名
        now = ctx.getMessage("now",b,Locale.US);
        System.out.println("\nEnglish message");
        System.out.println(hello);
        System.out.println(now);

        hello = ctx.getMessage("hello",a,Locale.CHINA);
        now = ctx.getMessage("now",b,Locale.CHINA);
        System.out.println("\n中文信息");
        System.out.println(hello);
        System.out.println(now);


                              

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值