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

简介: Spring-国际化信息02-MessageSource接口

概述

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


MessageSource接口方法


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

20170811035225375.jpg

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类结构


20170811035751918.jpg20170811035639325.jpg



其中:


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

20170811035959310.jpg


HierarchicalMessageSource接口最重要的两个实现类是

ResourceBundleMessageSource 和ReloadableResourceBundleMessageSource。


20170811040230446.jpg


它们基于Java的ResourceBundle基础类实现,允许仅通过资源名加载国际化资源。

ReloadableResourceBundleMessageSource提供了定时刷新功能,允许在不重启系统的情况下,更新资源的信息。

StaticMessageSource主要用于程序测试,它允许通过编程的方式提供国际化信息。

DelegatingMessageSource是为方便操作父MessageSource而提供的代理类。


ResourceBundleMessageSource


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


实例


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


20170812124301189.jpg


资源文件:

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);
    }
}



运行结果:

20170812125444503.jpg


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


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


ReloadableResourceBundleMessageSource


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


实例



20170812124218151.jpg

资源文件同上

通过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}


运行结果:


20170812125401913.jpg


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

相关文章
|
1月前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
125 0
|
1月前
|
前端开发 安全 Java
Spring Boot 三招组合拳,手把手教你打出优雅的后端接口
Spring Boot 三招组合拳,手把手教你打出优雅的后端接口
66 0
|
10天前
|
存储 Java 数据安全/隐私保护
Spring Boot中实现邮箱登录/注册接口
Spring Boot中实现邮箱登录/注册接口
|
8天前
|
Java 数据安全/隐私保护 网络架构
一个简单的示例在spring boot中实现国际化
一个简单的示例在spring boot中实现国际化
|
1月前
|
小程序 JavaScript Java
高校宿舍信息|基于Spring Boot的高校宿舍信息管理系统的设计与实现(源码+数据库+文档)
高校宿舍信息|基于Spring Boot的高校宿舍信息管理系统的设计与实现(源码+数据库+文档)
33 0
|
8天前
|
前端开发 Java 开发者
在Spring框架中,`PathMatcher`是用于进行URL路径匹配的接口
在Spring框架中,`PathMatcher`是用于进行URL路径匹配的接口
25 6
|
8天前
|
算法 Java API
在Spring Boot中实现接口签名验证通常涉及以下步骤
在Spring Boot中实现接口签名验证通常涉及以下步骤
33 4
|
23天前
|
设计模式 Java 关系型数据库
Spring的配置文件,如何配置端口号,,properties,yml获取配置项等方法,外观模式及其优缺点,日志代表的信息
Spring的配置文件,如何配置端口号,,properties,yml获取配置项等方法,外观模式及其优缺点,日志代表的信息
|
2天前
|
前端开发 Java Spring
spring接口版本控制方案及RequestMappingHandlerMapping接口介绍
spring接口版本控制方案及RequestMappingHandlerMapping接口介绍
|
2天前
|
缓存 前端开发 Java
Spring Boot中防止接口重复提交
Spring Boot中防止接口重复提交