PropertyPlaceholderConfigurer讀取配置文件
第一步:定義自己的Property;
package com.my.config.properties;
public class Property {
private static java.util.Properties property;
private Property() {
}
static void init(java.util.Properties props) {
property = props;
}
public static String getProperty(String key) {
return property.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return property.getProperty(key, defaultValue);
}
}
第二步:繼承PropertyPlaceholderConfigurer定義自己的PropertyPlaceholderConfigurer;
主要思想是通過PropertyPlaceholderConfigurer的mergeProperties方法獲取spring加載完成的鍵值對;
package com.my.config.properties;
import java.io.IOException;
import java.util.Properties;
public class PropertyPlaceholderConfigurer extends
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {
private static Properties props;
public Properties mergeProperties() throws IOException {
props = super.mergeProperties();
Property.init(props);
return props;
}
public static String getProperty(String key) {
return props.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return props.getProperty(key, defaultValue);
}
}
第三步:在application.xml中添加如下配置,profile.properties配置在windows環境變量中;<bean id="propertyConfigurer"
class="com.my.config.properties.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:${profile.properties}/*.properties</value>
</list>
</property>
</bean>
例子:在程序中可以直接使用Property.getProperty("CORPNO")得到相應的配置文件中的值。