在学习ApplicationContext对国际化支持的时候,发生中文乱码。
错误点:message_zh_CN.properties的文件编码不是以 ASCII 编码存储的。
(该properties文件用记事本打开时,以 ASCII 编码的中文是类似:\u6B22\u8FCE\u4F60 ,如果记事本显示的是正常中文,则出错了)
解决方案:
1)File>Settings>Editor>File Encodings,勾选上 :Transparent native-to-ascii conversion .
2)然后右键你的 .properties文件 ,选择:Mark as Properties,这时你的properties会变成如下。
3)打开.properties文件,将原本的中文删除 ,重新写入。
以下是我的国际化demo
1)beans.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">
<!--
驱动Spring调用messageSource Bean的setBasenames()方法
setBasenames():需要一个数组参数,使用list元素配置多个数组元素
-->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>i18n/message</value>
<!--如果有多个资源文件,列在此处-->
</list>
</property>
</bean>
</beans>
2)message_zh_CN.properties
hello=\u6B22\u8FCE\u4F60,{0}
now=\u73B0\u5728\u65F6\u95F4\u662F\uFF1A{0}
3)message_en_US.properties
hello=welcome,{0}
now=now is :{0}
4)I18nTest.class
package test.java;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
import java.util.Locale;
/**
* @Author:蜡笔小新
* @Date:2020/4/13 20:42
*/
public class I18nTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
String hello = ctx.getMessage("hello",new String[]{"蜡笔小新"}, Locale.getDefault(Locale.Category.FORMAT));
String now = ctx.getMessage("now",new String[]{String.valueOf(new Date())}, Locale.getDefault(Locale.Category.FORMAT));
System.out.println(hello);
System.out.println(now);
}
}
效果截图: