国际化(i18n)
概述
i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。在信息技术领域,国际化与本地化(英文:internationalization and localization)是指修改软件使之能适应目标市场的语言、地区差异以及技术需要。
java国际化
java自身支持国际化
java.util.Local
用于指定当前用户所属的语言环境等信息,Local包含了language信息和country信息。
java.util.ReourceBundle
用于查找绑定对应的资源文件。
配置文件命名规则
basenaem_language_country.properties
必须遵循命名规则,java才会识别。
basename
是必须的,语言和国家是可选的。
如果同时提供了context.properties
和context_zh_CN.propertes
两个配置文件,提供的locale
符合en_CN
,那么优先查找messages_en_CN.propertes
配置文件,如果没查找到,再查找messages.properties
配置文件。
所有的配置文件必须放在classpath中,一般放在resources目录下。
实例
测试
@Test
public void testCN() {
ResourceBundle bundle = ResourceBundle.getBundle("local", new Locale("zh", "CN"));
String value = bundle.getString("localName");
System.out.println("value = " + value);
/*value = China*/
}
@Test
public void testOther() {
//"local"就是配置文件的basename
ResourceBundle bundle1 = ResourceBundle.getBundle("local", new Locale("en", "US"));
String value = bundle1.getString("localName");
System.out.println("value = " + value);
/*value = USA*/
}
Spring6国际化
Spring国际化是通过
MessageSource
接口来支持的。
MessageSource接口
常见实现类
ResourceBundleMessageSource
:这是基于javaResourceBundle
基础类实现,仅允许通过资源名加载国际化资源。
ReloadadabelResourceBundleMessageSource
:它的功能和上面的类似,多了定时刷新功能,允许在不重启的情况下,更新资源。
StaticMessageSource
:允许通过编程的方式提供国际化信息。
Spring6国际化使用
国际化文件命名格式:基本名称_语言_国家.properties。
步骤
1、创建资源文件
message_zh_CN.properties
test=你好 {0}, 时间:{1}
message_en_US.properties
test=welcome {0}, time:{1}
{0}、{1}表示的是通过动态方式传递。
2、创建配置文件
<?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="basenames">
<list>
<value>message</value>
</list>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
</beans>
3、测试
@Test
public void testCN() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Object[] obj = new Object[]{"khan", new Date().toString()};
String value = context.getMessage("test", obj, Locale.CHINA);
System.out.println("value = " + value);
/*value = 你好 khan, 时间:Tue Jul 25 18:55:09 CST 2023*/
}
@Test
public void testUS() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Object[] obj = new Object[]{"louie", new Date().toString()};
String value = context.getMessage("test", obj, Locale.US);
System.out.println("value = " + value);
/*value = welcome louie, time:Tue Jul 25 18:55:09 CST 2023*/
}
输出乱码解决
同时还需要将配置文件中的内容做修改,不然会因为修改编码后导致文件中变为乱码格式保留。