• SpringResourceBundleMessageSource示例(转)


    对于支持国际化的应用程序,它需要能够为不同的语言环境解析文本消息。Spring的应用程序上下文能够通过键解析目标语言环境的文本消息。通常,一个语言环境的消息应存储在一个单独的属性文件中。此属性文件称为资源包。

    MessageSource是一个接口,它定义了几种解析消息的方法。该ApplicationContext接口扩展了此接口,以便所有应用程序上下文都能够解析文本消息。

    应用程序上下文将消息解析委托给具有确切名称的bean messageSourceResourceBundleMessageSource是最常见的MessageSource实现,它解决来自不同语言环境的资源包的消息。

    使用ResourceBundleMessageSource解析文本消息

    例如,您可以messages_en_US.properties为美国的英语创建以下资源包。资源包将从类路径的根目录加载。

    1)创建资源包

    messages_en_US.properties在spring应用程序的类路径中创建文件名。

    messages_en_US.properties
    msg.text=Welcome to howtodoinjava.com
     

    2)配置ResourceBundleMessageSource bean定义

    现在将ResourceBundleMessageSource类配置为bean名称"messageSource"。此外,您必须指定资源包的基本名称ResourceBundleMessageSource

    applicationContext.xml中
    <bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">
    
        <property name="basename">
    
            <value>messages</value>
    
        </property>
    
    </bean>

    资源包查找顺序

    1. 对于此messageSource定义,如果您查找其首选语言为英语的美国语言环境的文本消息messages_en_US.properties,则将首先考虑与语言和国家/地区匹配的资源包。
    2. 如果没有此类资源包或无法找到该消息,则messages_en.properties仅考虑与该语言匹配的消息。
    3. 如果仍无法找到此资源包,则messages.properties最终将选择所有语言环境的默认值。

    演示 - 如何使用MessageSource

    1)直接获取消息

    现在检查是否可以加载消息,运行以下代码:

    TestSpringContext.java
    public class TestSpringContext
    
    {
    
        @SuppressWarnings("resource")
    
        public static void main(String[] args) throws Exception
    
        {
    
            ApplicationContext context = newClassPathXmlApplicationContext("applicationContext.xml");
    
     
    
            String message = context.getMessage("msg.text", null, Locale.US);
    
             
    
            System.out.println(message);
    
        }
    
    }
     

    输出:

    Welcome to howtodoinjava.com

    2)在bean中实现MessageSourceAware接口

    很好,所以我们能够解决消息。但是,我们在这里直接访问,ApplicationContext所以看起来很容易。如果我们想要访问某些bean实例中的消息,那么我们需要实现ApplicationContextAware接口或MessageSourceAware接口。

    像这样的东西:

    EmployeeController.java
    public class EmployeeController implements MessageSourceAware {
    
     
    
        private MessageSource messageSource;
    
     
    
        public void setMessageSource(MessageSource messageSource) {
    
            this.messageSource = messageSource;
    
        }
    
     
    
        //Other code
    
    }

    现在,您可以使用此messageSource实例来检索/解析资源文件中定义的文本消息。

    转自:https://blog.csdn.net/u010675669/article/details/86488510

  • 相关阅读:
    乐观锁+悲观锁
    python读取大文件处理方式
    ionic集成jPush极光推送
    AngularJs中$http发送post或者get请求,SpringMVC后台接收不到参数值的解决办法
    ionic开发插件之ngCordova配置安装(搬运)
    使用Ionic进行移动端APP开发
    HashMap,LinkedHashMap,TreeMap的区别
    ubuntu下node、npm、bower简易安装
    Mongodb数据更新命令(update、save)
    mongoDb地理空间索引和查询
  • 原文地址:https://www.cnblogs.com/muxi0407/p/12124647.html
Copyright © 2020-2023  润新知