属性在ReloadableResourceBundleMessageSource中加载如下:
this.propertiesPersister.load(props, new InputStreamReader(is, encoding));
查看spring-context source code。在进一步的课程中,通过java.util.Propertiespublic void load(Reader reader) 方法读取文件,该方法将编码感知InputStreamReader(is, encoding) 作为参数。
这意味着常规的java.util.Properties 也可以加载不同的编码。
示例
PropertyReader.java
package com.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PropertyReader {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
List<String> locales = new ArrayList<String>(Arrays.asList("en", "ru", "de"));
for (String loc : locales) {
Locale locale = new Locale(loc);
String value = context.getMessage("example", null, locale);
System.out.println(value);
}
((AbstractApplicationContext) context).close();
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
</beans>
messages.properties
example=Example
messages_de.properties
example=Beispiel
messages_ru.properties
example=образец
没有默认编码的结果
注释 context.xml 中的属性
Example
обÑазеÑ
Beispiel
默认编码的结果
Example
образец
Beispiel
程序化方法的结果相同。