带有ResourceBundleMessageSource示例的Spring Resource捆绑包

在Spring中,您可以基于选定的语言环境,使用ResourceBundleMessageSource来解析属性文件中的文本消息。 请参阅以下示例:

1.目录结构

查看此示例的目录结构。

directory structure of this example

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);

	}
}

输出量

output

注意
确保您的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

下载源代码

下载它– Spring-MessageSource-Example.zip

翻译自: https://mkyong.com/spring/spring-resource-bundle-with-resourcebundlemessagesource-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值