《Spring Recipes》第二章笔记:Resolving Text Messages

《Spring Recipes》第二章笔记:Resolving Text Messages


问题


应用的在国际化时,需要使用多个不同locale的资源文件。

解决方案

Application接口提供了过根据Key从不同Locale的resource bundle中获取文本信息的功能。


(1)首先保证resource bundle为正确的格式:basename[_language][_country].properties,并存放在classpath的根目录下面。
(2)在配置文件中声明resource bundle的basename:设置org.springframework.context.support.ResourceBundleMessageSource的basename属性。

配置一个resource bundle:

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


配置多个resource bundle:
<beans>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>format</value>
      <value>exceptions</value>
      <value>windows</value>
    </list>
  </property>
</bean>
</beans>


(3)使用ApplicationContext接口的getMessage方法获取文本信息:
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
...
String alert = context.getMessage("alert.checkout", null, Locale.US);
System.out.println(alert);

注意

查找resource bundle的顺序:
    1. 如果getMessage方法中设置了Locale,优先查找 basename_language_country.properties文件。其中的language是Locale中设置的 language。
    2. 如果没有 basename_language_country.properties文件,则查找 basename_language.properties文件。
    3. 如果没有 basename_language.properties文件,则查找 basename.properties文件。
    4. 如果还没有在getMesage中传人default信息,并且没有 basename.properties文件,则容器抛出org.springframework.context.NoSuchMessageException异常。

在resource bundle中使用占位符

可以在resource bundle中使用{n}(n 为>=0的整数),getMessage方法的第二个参数中可以传人一个Object数组,用来替换占位符的值。
例:
resource bundle:
alert.checkout=A shopping cart costing {0} dollars has been checked out at {1}.

bean:
String alert = context.getMessage("alert.checkout",new Object[] { 4, new Date() }, Locale.US);

注意:
  • 如果传入的数组中元素的个数少于占位符的个数,容器会按顺序用数组元素替换占位符。多出来的占位符会按照{n}的形式返回。
  • 如果传人的数组中元素的个数多于占位符的个数,容器会按顺序用数组元素替换占位符。多出来的数组元素不会使用。


你可能感兴趣的:(spring)