spring-Internationalization Information 02-messagesource interface __spring

Source: Internet
Author: User
Tags getmessage i18n locale

Overview Messagesource Interface method Messagesource class structure Resourcebundlemessagesource instance Reloadableresourcebundlemessagesource instance

Guide

spring-Internationalization Information 01-Basic knowledge

spring-Internationalization Information 02-messagesource interface

spring-Internationalization Information 03-container-level internationalization information Resources Overview

Spring defines the Messagesource interface for accessing internationalized information and provides several Easy-to-use implementation classes. Messagesource Interface Method

We first look at the source code, first to understand the interface of several important methods

String GetMessage (String code, object[] args, string defaultmessage, Locale Locale)
The code represents the name of the property in the Internationalized resource, args the run-time parameters used to pass the formatted string placeholder, and returns the default information specified by the Defaultmessage parameter when the resource cannot find the corresponding property name; Locale represents the localized object;

String GetMessage (String code, object[] args, Locale Locale) throws nosuchmessageexception;

Similar to the above method, it simply throws a nosuchmessageexception exception when the corresponding property name in the resource is not found;

String getMessage (messagesourceresolvable resolvable, Locale Locale) throws nosuchmessageexception;

Messagesourceresolvable encapsulates the property name, parameter array, and default information, and its functionality is the same as the first interface method. Messagesource class Structure

which

The Hierarchicalmessagesource interface adds two methods to build the messagesource structure of the parent-child hierarchy, Setparentmessagesource (messagesource parent) method is used to set the parent Messagesource, and the Getparentmessagesource () method is used to return the parent Messagesource.

The two most important implementation classes for the Hierarchicalmessagesource interface are
Resourcebundlemessagesource and Reloadableresourcebundlemessagesource.

They are based on the Java ResourceBundle base class implementation, allowing internationalization resources to be loaded only through resource names. Reloadableresourcebundlemessagesource provides a timed refresh feature that allows you to update resource information without restarting the system. Staticmessagesource is primarily used for program testing, which allows the internationalization of information to be provided programmatically. Delegatingmessagesource is a proxy class that is provided to facilitate the operation of the parent Messagesource. Resourcebundlemessagesource

The implementation class allows the user to specify a resource name (including the fully qualified resource name of the classpath) through Beanname, or specify a set of resource names through Beannames. instance

Code is hosted to Github-> Https://github.com/yangshangwei/SpringMaster

Resource file:

Greeting.common=how are you {0}?,today are {1}
Greeting.morning=good Morning {0}! now is {1,time,short}
Greeting.afternoon=good Afternoon {0}! Now is {1,date,long}

Configuring Beans through Resourcebundlemessagesource

<?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>

Test class

Start the spring container and access the configured internationalization resources via 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 Class

        Pathxmlapplicationcontext ("Classpath:com/xgj/ioc/i18n/messagesource/beans.xml"); Gets the Messagesource bean messagesource Messagesource = Ctx.getbean ("resource", Messagesource.class)

        ;

        Dynamic parameter object[] Objs = {"Xiaogongjiang", New GregorianCalendar (). GetTime ()};

        Gets the internationalized information formatted 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);
 }
}

Run Result:

With spring we do not need to load localized resource files for different languages, countries or regions separately, and we can load the entire set of internationalized resource files through the resource name alone. In addition, we do not need to explicitly use the Messageformat operation internationalization information, only through the messagesource# getMessage () method can complete the operation.

Compare the difference with the http://blog.csdn.net/yangshangwei/article/details/76946002#resourceboundle here. Reloadableresourcebundlemessagesource

The only difference between this implementation analogy and resourcebundlemessagesource is that it can periodically refresh the resource file to perceive changes in the resource file without restarting the application. Many production systems need to run for a long time, and the system reboot will bring a great negative effect to the operation. At this point, the implementation class can be used to solve the problem instance of internationalization information update

Resource File Ibid.

Configuring Resources through 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://ww W.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/util HTTP://WWW.SP Ringframework.org/schema/util/spring-util.xsd "> <bean id=" Resource "class=" Org.springframework.context. Support. Reloadableresourcebundlemessagesource "> <property name=" basenames "ref=" Resourcelist "/> <!--brushes The period of the new resource file, in seconds--> <property name= "Cacheseconds" value= "5"/> </bean> <util:list id= "Res Ourcelist "> <value>i18n/fmt_resource</value> </util:list> </beans> 

We use the Cacheseconds property to let the Reloadableresourcebundlemessagesource refresh the resource file every 5 seconds (in real applications, the refresh cycle can not be too short, otherwise frequent refresh will bring negative performance effects, Generally not recommended less than 30 minutes). Cacheseconds The default value of 1 means never refreshing , at which point the functionality of the implementation class is reduced to Resourcebundlemessagesource functionality.

Test class:

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/reloadable

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

Let the program sleep for 20 seconds, during which we change the Greeting.common in Fmt_resource_en_us.properties to

Greeting.common=***how Are you {0}?,today is {1}

Run Result:

The format information of two times output corresponds to the content before and after the change, and the adjustment of localized resource file is automatically effective.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.