How spring dynamically loads the contents of the properties file

Source: Internet
Author: User
Tags getmessage i18n

1. Configure your properties path in XML:

<bean id= "Messagesource" class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource" >

<property name= "Basenames" >

<list> <!--Specifies the resource file base name JDBC is a file name and does not contain an extension--

<value>classpath:resource/jdbc</value>

</list>

</property>

</bean>

2. Get Webapplicationcontext (requires HttpServletRequest request) ServletContext ServletContext = Request.getsession (). Getservletcontext (); Webapplicationcontext CTX = webapplicationcontextutils. Getrequiredwebapplicationcontext (ServletContext);

3. Get middle key value by Webapplicationcontext String msg = ctx.getmessage ("Jdbc.url", null, Locale.china);

--------------------------------------------------------------------------------------------------------------- -

Spring's messagesource has two common implementations ReloadableresourcebundlemessagesourceAnd Resourcebundlemessagesource。 There are some differences in the configuration of these two classes. My original used Resourcebundlemessagesource, it is typically configured as follows: <bean id= "Messagesource"
class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource" >
<property name= "Parentmessagesource" ref= "Bizmessagesource"/>
<property name= "Basenames" >
<list>
<value>resources.cls-web-resources</value>
<value>resources.cls-web-resources-definitions</value>
<value>resources.cls-web-resources-menu</value>
</list>
</property>
</bean> in comparison Reloadableresourcebundlemessagesourcethe configuration:<bean id= "Messagesource"
class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource" >
<property name= "Parentmessagesource" ref= "Bizmessagesource"/>
<property name= "Fallbacktosystemlocale" ><value>false</value></property>
<property name= "Basenames" >
<list>
<value> classpath:Resources /Cls-web-resources</value>
<value> classpath:Resources /Cls-web-resources-definitions</value>
<value> classpath:Resources /Cls-web-resources-menu</value>
</list>
</property>
</bean> the reason is ReloadableresourcebundlemessagesourceInternal use of Defaultresourceloader to load ResourceBundle, while Resourcebundlemessagesourcethe interior is directly using the Java.util.ResourceBundle. Getbundle (String baseName,locale locale, ClassLoader Loader) to obtain the i18n file information, and ResourceBundle is to use the "." As the basename delimiter (which is also our usual form),So there are some differences in the front configuration. Also if you do not set the " Fallbacktosystemlocale"Then, if your incoming locale is null or resourcebundle does not have a configuration file for that locale, then it will return the message under the locale of Locale.getdefault (). This setting defaults to True, that is, if the corresponding ResourceBundle is not found, the system will always appear as a resource in Chinese. It is recommended to turn off this setting, or fallbacklocale long time no meaning。 There's also a useful setting for " Usecodeasdefaultmessage”, default is False, so that when spring does not find Messagekey in ResourceBundle, it throws nosuchmessageexception, sets it to true, does not find no exception, and instead uses Messagekey as the return value. Resourcebundlemessagesource and Relo in----------------------------------------------------------------------------------Spring Adableresourcebundlemessagesource find the difference between resources:

1.ResourceBundleMessageSource cannot specify encoding in XML configuration:

<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBundleMessageSource" >

<property name= "Basenames" >

<list>

<value >error</value >

<value >message</value >

</list>

</property>

</bean>

And Reloadableresourcebundlemessagesource can specify the encoding, for example:

<bean id= "Messagesource" class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource" >

<property name= "defaultencoding" value = "GBK"/>

<property name= "basename" value = "message"/>

</bean>

2. Load resource files in different ways:

1). Take a look at their source code below:

Resourcebundlemessagesource loading, using the Classutils.getdefaultclassloader () loader, the Getdefaultclassloader method code is as follows:

P lic static ClassLoader Getdefaultclassloader ()

{

ClassLoader cl = null;

try {

CL = Thread.CurrentThread (). Getcontextclassloader ();

}

catch (Throwable ex) {

Logger.debug ("Cannot access thread context classloader-falling back to System class loader", ex);

}

if (CL = = NULL)

{

CL = ClassUtils.class.getClassLoader ();

}

return CL;

}

This is also the default way for the JVM to load, get the ClassLoader from the current thread and, if not, get the class loader for the class itself

2). Reloadableresourcebundlemessagesource also uses the Classutils.getdefaultclassloader () loader by default, and it loads resources in the following way:

P LIC Resource getresource (String location)

{

Assert.notnull (location, "must is not null");

if (Location.startswith ("classpath:")) {

return new Classpathresource (Location.s string ("Classpath:". Length ()), getClassLoader ());

}

Try

{

URL url = new URL (location);

return new Urlresource (URL);

}

catch (Malformedurlexception ex)

{

return Getresourcebypath (location);

}

}

3). Summary: Resourcebundlemessagesource load the resource file from the ClassLoader, you can find it,

Reloadableresourcebundlemessagesource load, the default use of Defaultresourceloader, he will first determine whether the resource path with classpath: prefix, if any, with Classpathresource to load the resource file, if not try to use the URL of the file protocol to access, and then not in the ContextPath that is web-inf under the search.

Here's an example of a spring Messagesource:

1. We create a new spring message file Beans-message.xml with the following configuration:

<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBundleMessageSource" >

<property name= "Basenames" >

<list>

<value >error</value>

<value >message</value >

</list>

</property>

</bean>

2. This configuration assumes that there are two resource files (resource bundles) in your classpath, which are error, message. With ResourceBundle, any request to parse a message is processed using the standard way of parsing the message in the JDK. For the purposes of the example, assume that the contents of the Message_zh_cn.properties resource file are ...

Msg.common.serverBusy = \ non \ Regular \ Hug apology, \ system \ Ten \ branch \ fan \ busy \!

#非常抱歉, the system is very busy!

Msg.argument.required={0}\ is \ \ \ \ \ \ \ \ \ \ \ n

#{0} is a required entry!

3. Write a test class again:

P Lic class Messagetest {

P lic static void Main (string[] args) {

Messagesource resources = new Classpathxmlapplicationcontext ("Beans-message.xml");

String message = Resources.getmessage ("Msg.common.serverBusy", NULL, "Default", null);

SYSTEM.OUT.PRINTLN (message);

String message1 = resources.getmessage ("msg.argument.required", new object[] {"' Contact method '}, NULL, Locale.china);

System.out.println (MESSAGE1);

}

}

The result is entered as:

Very sorry, the system is very busy!

' Contact information ' is a required item!

3. In our project, Messagesource will not be used alone, usually we will use it with our own business, when we can directly use its own method, we can also add our own logic: for example, a custom message class:

P Lic class Messagesourcehelper {

Private Resourcebundlemessagesource Messagesource;

P Lic string GetMessage (String code, object[] args, string defaultmessage, locale locale) {

String msg = messagesource.getmessage (code, args, defaultmessage, locale);

return msg! = null? Msg.trim (): msg;

}



P lic void Setmessagesource (Resourcebundlemessagesource messagesource) {

This.messagesource = Messagesource;

}

}

Inject in Beans-message.xml:

<bean id= "Messagesourcehelper" class= "Com.myspring.message.MessageSourceHelper" >

<property name= "Messagesource" >

<ref local= "Messagesource"/>

</property>

</bean>

4. We can add our own business to the Messagesourcehelper, and after injecting the dependency, we can call the methods in Messagesourcehelper in other classes.

5. Theory brief: The ApplicationContext interface extends the Messagesource interface, thus providing the capability of message processing (i18n or internationalization). Used with Hierarchicalmessagesource, it can also handle nested messages, which are the basic interfaces that spring provides for processing messages. Let's take a quick look at the method it defines:

· String GetMessage (String code, object[] args, string default, Locale Loc): The basic method used to get messages from Messagesource. If no message is found in the specified locale, the default message is used. The parameters in args will use the Messageformat in the standard class library as the replacement value in the message.

· String GetMessage (String code, object[] args, Locale Loc): Essentially the same as the previous method, the difference is: No default value is specified, and if no message is found, an NOS is thrown Hmessageexception exception.

· String getMessage (messagesourceresolvable resolvable, locale locale): The properties used in the methods above are encapsulated in a messagesourceresolvable implementation, This method can specify the messagesourceresolvable implementation.

When a applicationcontext is loaded, it automatically finds beans in the context that have been defined as Messagesource types. The name of this bean must be messagesource. If found, then all calls to the above method will be delegated to the bean. Otherwise, ApplicationContext will look in its parent class for a bean with the same name. If so, take it as a messagesource. If it does not eventually find any source of the message, an empty staticmessagesource will be instantiated so that it can accept the call of the above method.

Spring currently offers two Messagesource implementations: Resourcebundlemessagesource and Staticmessagesource. They all inherit nestingmessagesource in order to be able to handle nested messages. Staticmessagesource is rarely used, but it can be programmed to add messages to a message source. Resourcebundlemessagesource will use a little more.

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.