Spring i18n – ResourceBundleMessageSource

Spring i18n – ResourceBundleMessageSource

https://howtodoinjava.com/spring-core/resolving-text-messages-in-spring-resourcebundlemessagesource-example/

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

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

应用程序上下文将消息解析委托给确切名称为messageSource的 Bean。 ResourceBundleMessageSource是最常见的MessageSource实现,用于解析来自不同区域的资源包中的消息。

1. 使用ResourceBundleMessageSource解析消息

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

1.1. 创建资源包

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

messages_en_US.properties

msg.text=Welcome to howtodoinjava.com

1.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>

2. 资源包查找顺序

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

3. 演示 – 如何使用MessageSource

3.1. 直接获取消息

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

TestSpringContext.java

public class TestSpringContext 
{
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception 
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        String message = context.getMessage("msg.text", null, Locale.US);

        System.out.println(message);
    }
}

输出:

Console

Welcome to howtodoinjava.com

3.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实例来检索/解析资源文件中定义的文本消息。

学习愉快!