在Spring中,您可以基于选定的语言环境,使用ResourceBundleMessageSource
来解析属性文件中的文本消息。 请参阅以下示例:
1.目录结构
查看此示例的目录结构。
2.属性文件
创建两个属性文件,一个用于英文字符( messages_en_US.properties
),另一个用于中文字符( messages_zh_CN.properties
)。 将其放入项目类路径(请参见上图)。
文件:messages_en_US.properties
customer.name=Yong Mook Kim, age : {0}, URL : {1}
文件:messages_zh_CN.properties
customer.name=\ufeff\u6768\u6728\u91d1, age : {0}, URL : {1}
' \ ufeff \ u6768 \ u6728 \ u91d1 '是中文的Unicode字符。
注意
为了正确显示中文字符,您必须使用“ native2ascii ”工具将中文字符转换为Unicode字符。
3. Bean配置文件
将属性文件包括到Bean配置文件中。 “ messages_en_US.properties ”和“ messages_zh_CN.properties ”在Spring中都被视为一个文件,您只需要包含一次文件名,Spring就会自动找到正确的语言环境。
<?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-2.5.xsd">
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>locale\customer\messages</value>
</property>
</bean>
</beans>
PS假设两个文件都位于“ resources \ locale \ customer \”文件夹中。
4.运行
package com.mkyong.common;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context
= new ClassPathXmlApplicationContext("locale.xml");
String name = context.getMessage("customer.name",
new Object[] { 28,"http://www.mkyong.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
String namechinese = context.getMessage("customer.name",
new Object[] {28, "http://www.mkyong.com" },
Locale.SIMPLIFIED_CHINESE);
System.out.println("Customer name (Chinese) : " + namechinese);
}
}
输出量
注意
确保您的Eclipse能够显示中文输出 。
说明
1.在context.getMessage()
,第二个参数是消息参数,您必须将其作为对象数组传递。 如果没有可用的参数值,则只需传递一个null即可。
context.getMessage("customer.name",null, Locale.US);
2. Locale.US将从“ messages_en_US.properties ”中检索消息,而Locale.SIMPLIFIED_CHINESE将从“ messages_zh_CN.properties ”中检索消息 。
更多 …
阅读本文,了解如何访问bean中的MessageSource 。
下载源代码
翻译自: https://mkyong.com/spring/spring-resource-bundle-with-resourcebundlemessagesource-example/