<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans SYSTEM "spring-beans.dtd"><beans><!-- 使用该实现类的一个理由是:可以设置文件编码,从而避免中文乱码。还可以动态刷新资源 --><beanid="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><propertyname="basenames"><list><!-- the family of resource bundles --><value>my_message_source</value></list></property><!-- 避免中文乱码 --><propertyname="defaultEncoding"><value>UTF-8</value></property></bean></beans>
简单测试
package com.willhonor.test.useMessageSource;import java.util.Locale;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;publicclassTest_use_message_source_i18n{@Testpublicvoidtest_use_1()throws Exception {
String pathA ="com/willhonor/test/configs/application.j.xml";
String[] path =newString[]{pathA};
ClassPathXmlApplicationContext context =newClassPathXmlApplicationContext(path);// ch
String can = context.getMessage("application-name",newObject[]{}, Locale.CHINESE);
System.out.println(can);
String ca = context.getMessage("author",newObject[]{}, Locale.CHINESE);
System.out.println(ca);
String cv = context.getMessage("version",newObject[]{}, Locale.CHINESE);
System.out.println(cv);// en
String ean = context.getMessage("application-name",newObject[]{}, Locale.ENGLISH);
System.out.println(ean);
String ea = context.getMessage("author",newObject[]{}, Locale.ENGLISH);
System.out.println(ea);
String ev = context.getMessage("version",newObject[]{}, Locale.ENGLISH);
System.out.println(ev);//
context.close();}@Testpublicvoidtest_use_locale()throws Exception {
System.out.println(Locale.ENGLISH.getLanguage());// en, language
System.out.println(Locale.CHINESE.getLanguage());// ch, language
System.out.println(Locale.CHINA.getCountry());// cn, country}}
测试执行结果如下(结果达到预期)
...
# 省略 spring 日志打印...
应用名称
作者
版本
application name
author
version
...
# 省略 spring 日志打印...