有时候需要使用资源国际化来定义和处理一些字段。本文是一个简单的使用例子用于展示在基于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);
}
}