使用spring实现资源国际化

有时候需要使用资源国际化来定义和处理一些字段。本文是一个简单的使用例子用于展示在基于java注解的配置中配置spring资源国际化的类并使用其获取prop文件中的属性。


1、创建资源文件

本文示例使用的资源文件为一个属性文件,默认的属性文件名称为i18n.properties,存放在工程的类路径下的i18n目录下。实际使用中可以针对需要添加针对不同语音的属性文件,如:

i18n_en_US.properties、i18n_zh_CN.properties等。本例中的默认属性配置文件中的内容如下:

munu.btn1.title=\u5B89\u9632
menu.btn2.title=\u670D\u52A1
menu.btn3.title=\u6211\u7684
munu.btn3.sub1.title=\u4E3B\u9875

2、配置bean

本文使用给予java注解的配置。主要时创建一个org.springframework.context.support.ResourceBundleMessageSource的bean实例。源码如下:

package api.landsem.base.configuration;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc  
@ComponentScan({"api.landsem.base.bean"})
@ImportResource("classpath:applicationContext-*.xml")
public class RootConfiguration {

	@Bean("messageSource")
	public MessageSource getResourceBundleMessageSourc() {
		ResourceBundleMessageSource resource = new ResourceBundleMessageSource();
		resource.setBasename("i18n/i18n");
		return resource;
	}
}

3、读取资源属性文件

在java中使用创建的MessageSource bean来读取属性文件,如下为测试源码:

package api.landsem.base.test;

import java.util.Locale;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

public class PropertiesTest extends BaseTest{
	private static final Logger logger = Logger
			.getLogger(PropertiesTest.class);	
	
	@Autowired
	private MessageSource mMessageSource;

	@Test
	public void test() {
		String msg = mMessageSource.getMessage("munu.btn1.title", null, Locale.getDefault());
		logger.info(msg);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值