PropertyPlaceholderConfigurer讀取配置文件

陌上開花 9年前發布 | 72K 次閱讀 Spring JEE框架

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

 本文由用戶 陌上開花 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!