spring 读取properties文件属性

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

       比如在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>就无需做上述操作

猜你喜欢

转载自a-john.iteye.com/blog/2235889