PropertyPlaceholderConfigurer读取配置文件

陌上开花 9年前

第一步:定义自己的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")得到相应的配置文件中的值。