您的位置:首页 > 编程语言 > Java开发

spring 读取properties文件属性

2015-08-16 20:18 465 查看

       同一份代码要在不同的环境下运行,不同环境的配置也各不相同,代码要用到的属性就不能写死,需要根据不同环境下的的配置文件去读取:

       比如在tomcat下有一个etc文件,里面有一个配置文件demo.properties

 

message=hello world

 如果要在代码中获取该message属性的值,可以通过以下方式:

 

一,在applicationContext.xml文件中配置一下内容:

 

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${catalina.home}/etc/demo.properties</value>
</list>
</property>
</bean>

 二,建一个工具类:

 

 

public class PropertiesConfigLoad {
@Value("${message}")
private String message;

public String getMessage() {
return message;
}

}

 三,在xml文件中创建上述工具类的bean

 

 

<bean id="propertiesConfigLoad"
class="com.olymtech.cs.base.datads.util.PropertiesConfigLoad"></bean>

 四,在代码获取message属性的值

 

 

@Resource(name = "propertiesConfigLoad")
private PropertiesConfigLoad propertiesConfigLoad;

String message = propertiesConfigLoad.getMessage();

 这样就可以获取message的值(hello world)了。

 

需要注意的是,这里配置的<value>file:${catalina.home}/etc/demo.properties</value>需要在启动tomcat或者在电脑的环境变量中设置相应的catalina.home的值,如果文件地址是<value>classpath:demo.properties</value>就无需做上述操作

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: