Spring-国际化信息02-MessageSource接口

导读

Spring-国际化信息01-基础知识

Spring-国际化信息02-MessageSource接口

Spring-国际化信息03-容器级的国际化信息资源


概述

spring定义了访问国际化信息的MessageSource接口,并提供了几个易用的实现类.


MessageSource接口方法

我们先看下源码,先来了解一下该接口的几个重要方法

这里写图片描述

  • String getMessage(String code, Object[] args, String defaultMessage, Locale locale)
    code表示国际化资源中的属性名;args用于传递格式化串占位符所用的运行期参数;当在资源找不到对应属性名时,返回defaultMessage参数所指定的默认信息;locale表示本地化对象;

  • String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException;

    与上面的方法类似,只不过在找不到资源中对应的属性名时,直接抛出NoSuchMessageException异常;

  • String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;

    MessageSourceResolvable 将属性名、参数数组以及默认信息封装起来,它的功能和第一个接口方法相同。


MessageSource类结构

这里写图片描述

这里写图片描述

其中:

HierarchicalMessageSource接口添加了两个方法,建立父子层级的MessageSource结构 ,setParentMessageSource (MessageSource parent)方法用于设置父MessageSource,而getParentMessageSource()方法用于返回父MessageSource。

这里写图片描述

HierarchicalMessageSource接口最重要的两个实现类是
ResourceBundleMessageSource 和ReloadableResourceBundleMessageSource。

这里写图片描述

  • 它们基于Java的ResourceBundle基础类实现,允许仅通过资源名加载国际化资源。
  • ReloadableResourceBundleMessageSource提供了定时刷新功能,允许在不重启系统的情况下,更新资源的信息。
  • StaticMessageSource主要用于程序测试,它允许通过编程的方式提供国际化信息。
  • DelegatingMessageSource是为方便操作父MessageSource而提供的代理类。

ResourceBundleMessageSource

该实现类允许用户通过beanName指定一个资源名(包括类路径的全限定资源名),或通过beanNames指定一组资源名.

实例

代码已托管到Github—> https://github.com/yangshangwei/SpringMaster

这里写图片描述

资源文件:

greeting.common=How are you {0}?,today is {1}
greeting.morning=Good Morning {0}! now is {1,time,short}
greeting.afternoon=Good Afternoon {0}! now is {1,date,long}

通过ResourceBundleMessageSource配置Bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util 
     http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="resource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" ref="resourceList"/>
    </bean>

    <util:list id="resourceList">
        <value>i18n/fmt_resource</value>
    </util:list>

</beans>

测试类

启动Spring容器,并通过MessageSource访问配置的国际化资源

package com.xgj.ioc.i18n.messageSource;

import java.util.GregorianCalendar;
import java.util.Locale;

import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MessageSourceTest {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/i18n/messageSource/beans.xml");

        // 获取MessageSource的Bean
        MessageSource messageSource = ctx.getBean("resource",
                MessageSource.class);

        // 动态参数
        Object[] objs = { "Xiaogongjiang", new GregorianCalendar().getTime() };

        // 获取格式化的国际化信息
        String msg1 = messageSource.getMessage("greeting.common", objs,
                Locale.CHINESE);

        String msg2 = messageSource.getMessage("greeting.morning", objs,
                Locale.US);

        String msg3 = messageSource.getMessage("greeting.afternoon", objs,
                Locale.CHINESE);

        System.out.println(msg1);
        System.out.println(msg2);
        System.out.println(msg3);

    }
}

运行结果:

这里写图片描述

通过Spring我们无须再分别加载不同语言、不同国家/地区的本地化资源文件,仅仅通过资源名就可以加载整套的国际化资源文件。此外,我们无须显式使用MessageFormat操作国际化信息,仅通过MessageSource# getMessage()方法就可以完成操作了.

比较下 和 http://blog.csdn.net/yangshangwei/article/details/76946002#resourceboundle 这里的区别。


ReloadableResourceBundleMessageSource

该实现类比之于ResourceBundleMessageSource的唯一区别在于它可以定时刷新资源文件,以便在应用程序不重启的情况下感知资源文件的变化。很多生产系统都需要长时间持续运行,系统重启会给运行带来很大的负面影响。这时,通过该实现类就可以解决国际化信息更新的问题

实例

这里写图片描述

资源文件同上

通过ReloadableResourceBundleMessageSource配置资源

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util 
     http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="resource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames" ref="resourceList"/>
        <!-- 刷新资源文件的周期,以秒为单位 -->
        <property name="cacheSeconds" value="5"/>
    </bean>

    <util:list id="resourceList">
        <value>i18n/fmt_resource</value>
    </util:list>

</beans>

我们通过cacheSeconds属性让ReloadableResourceBundleMessageSource每5秒钟刷新一次资源文件(在真实的应用中,刷新周期不能太短,否则频繁的刷新将带来性能上的负面影响,一般不建议小于30分钟)。cacheSeconds默认值为-1表示永不刷新,此时,该实现类的功能就蜕化为ResourceBundleMessageSource的功能。

测试类:

package com.xgj.ioc.i18n.reloadableResourceBundleMessageSource;

import java.util.GregorianCalendar;
import java.util.Locale;

import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ReloadableResourceBundleMessageSourceTest {

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

        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/i18n/reloadableResourceBundleMessageSource/beans.xml");

        MessageSource messageSource = ctx.getBean("resource",
                MessageSource.class);

        Object[] objects = { "XiaoGongJiang", new GregorianCalendar().getTime() };

        for (int i = 0; i < 2; i++) {
            String msg = messageSource.getMessage("greeting.common", objects,
                    Locale.US);
            System.out.println(msg + "\nsleep 20S");
            Thread.sleep(20000);
        }
    }
}

让程序睡眠20秒钟,在这期间,我们将fmt_resource_en_US.properties 中的 greeting.common改为

greeting.common=***How are you {0}?,today is {1}

运行结果:

这里写图片描述

两次输出的格式化信息分别对应更改前后的内容,也即本地化资源文件的调整被自动生效了

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring框架提供了很好的国际化(i18n)支持,其核心是ResourceBundleMessageSource类,这个类实现了MessageSource接口,可以通过其提供的方法获取国际化的消息文本。国际化配置包含以下步骤: 1. 在Spring配置文件中配置ResourceBundleMessageSource Bean。 2. 创建属性文件,包含不同语言版本的消息文本。 3. 在JSP页面或者Java代码中使用MessageSource获取对应语言版本的消息文本。 具体操作如下: 1. 在Spring配置文件中添加如下配置: ``` <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages"/> </bean> ``` basename属性指定了消息文件的基础名称,这里的值是“messages”,表示消息文件名为“messages.properties”(默认语言)和“messages_zh_CN.properties”(中文语言)。 2. 创建消息文件。 在classpath下创建一个名为“messages.properties”的文件,内容如下: ``` message.hello=Hello, World! ``` 然后在同一个目录下创建一个名为“messages_zh_CN.properties”的文件,内容如下: ``` message.hello=你好,世界! ``` 这里我们定义了一个名为“message.hello”的消息文本,分别提供了英文和中文两种语言版本。 3. 在JSP页面或者Java代码中使用MessageSource获取对应语言版本的消息文本。 在JSP页面中,可以使用spring:message标签获取消息文本: ``` <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <spring:message code="message.hello"/> ``` 在Java代码中,可以注入MessageSource,并使用其getMessage方法获取消息文本: ``` @Autowired private MessageSource messageSource; String message = messageSource.getMessage("message.hello", null, Locale.getDefault()); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小工匠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值