Spring 中的国际化Message的简单例子(ApplicationContext) 不跟框架集成的版本

首先,建立一个描述message的XML文件,名为messages.xml 
    
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <!-- 资源国际化测试 --> 
    <bean id="messageSource"        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">        <property name="basenames"> 
            <list> 
                <value>org/rjstudio/spring/properties/messages</value> 
            </list> 
        </property> 
    </bean> 
</beans> 
    
    这个Bean的id是定死的,只能为“messageSource”。这里的Class需要填入MessageSource接口的实现。其中,在我看的书中只提及了两个类,一个是:ResourceBundleMessageSource,另一个则是ReloadableResourceBundleMessageSource。其中,后者提供了无需重启就可重新加载新配置的特性。 
    
    list节点的value子节点中的body值“org/rjstudio/spring/properties/messages”,是指org.rjstudio.spring.proerties包下的以messages为主要名称的properties文件。比如说,以Locale为zh_CN为例,Spring会自动在类路径中在org.rjstudio.spring.properties包下按照如下顺序搜寻配置文件并进行加载: 
    
    
    
    接下来,让我们在org.rjstudio.spring.properties下,建立两个messages的属性文件。一个名为messages_zh_CN.properties,另一个为messages_en_US.properties,分别对应国际化中的中国和美国。 
    
    在这两个属性文件中分别建立一个userinfo属性。 
        中国为:userinfo=当前登陆用户[{0}] 登陆时间[{1}] 
        美国为:userinfo=current login user:[{0}] login time:[{1}] 
    
    好了,一切就绪,接下来可以写段代码来测试了。。建个类,写个测试Main方法。 
    
    
    
    
    public class MessageTest { 
        public static void main(String[] args) { 
            ApplicationContext ctx = new ClassPathXmlApplicationContext("messages.xml"); 
            Object[] arg = new Object[] { "Erica", Calendar.getInstance().getTime() }; 
            String msg = ctx.getMessage("userinfo", arg,Locale.CHINA); 
            System.out.println("Message is ===> " + msg); 
        } 
    } 
    
    最后输出的结果是:Message is ===> 当前登录用户:[Erica] 登录时间:[07-6-8 上午10:20] 
    
    ctx.getMessage("userinfo", arg,Locale.getDefault());这个方法,传入的三个参数,第一个是properties文件中对应的名。arg为一个对象数组,我们在properties里面放置了两个变量,[{0}]和[{1}],Spring会为我们给它们赋值。而最后则需要传入一个Local。这里用 Locale.CHINA代表中国。如果我们用Locale.US,则输出会变为: 
    
    Message is ===> current login user:[Erica] login time:[6/8/07 10:59 AM] 
    
    OK,到这里,就到这里。

原文地址:https://www.cnblogs.com/toSeeMyDream/p/4108651.html