2011年6月3日 星期五

spring 使用 application 中定義的 properties

問題:
在applicationContext 中常會設定一個properties 來載入一些設定檔
通常是
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
.....
</bean>

但發現 這個 PropertyPlaceholderConfigurer 類別不提供它的 java.util.Properties 讓我們用。
但是它的父類別org.springframework.core.io.support.PropertiesLoaderSupport 有提供一個protected method
protected Properties mergeProperties() throws IOException

所以這邊提供一種做法是,自己寫一個Class 繼承 PropertiesLoaderSupport ,然後裡面提供一個method

public class MyPropertyPlaceholderConfigurer extends
  PropertyPlaceholderConfigurer {

  Properties mergedProperties;

   public Properties getMergedProperties() throws IOException {
     if (mergedProperties == null) {

       mergedProperties = mergeProperties();

     }
     return mergedProperties;

   }
}

然後 applicationContext 裡的 propertyConfigurer設定改成
<bean id="propertyConfigurer" class="MyPropertyPlaceholderConfigurer">

......
這樣就可以在之後使用這個bean 取得 properties

沒有留言: