2011-03-04 94 views
4

我有在.properties文件中的屬性列表。 現在我正在管理那些屬性文件,其中PropertyPlaceholderConfigurer如何從bean的方法訪問Spring託管屬性?

我想訪問其中一個方法的屬性值。 任何人都可以請建議如何實現?

例如

connection.properties 
dev.url = "http://localhost:8080/" 
uat.url = "http://xyz.com" 

現在我已經通過specifing connection.properties

我已經一種方法基於部署 的模式,其讀取URL,以便基體上的部署模式欲配置`PropertyPlaceholderConfigurer豆使用屬性文件更改網址。

請讓我知道這是否是正確的方法。

如果您有任何建議,請給。

回答

3

PropertyPlaceholderConfigurerdoes not expose其屬性。然而,您可以輕鬆地使用例如文件重新閱讀屬性文件。 PropertiesLoadUtils

PropertiesLoaderUtils.loadProperties(
     new ClassPathResource("/connection.properties")); 
0

你正在尋找什麼不清楚,但我有它基於環境的加載性能效用及其對(DEV,PROD)

public class EnvironmentalPlaceHolderConfigurer extends PropertyPlaceholderConfigurer 
     implements InitializingBean { 

    private Resource overrideLocation; 

    public void setOverrideLocation(Resource overrideLocation) { 
     this.overrideLocation = overrideLocation; 
    } 
    if(overrideLocation != null){ 
      if(overrideLocation.exists()) 
       super.setLocation(overrideLocation); 
      else{ 
       logger.warn("Unbale to find "+overrideLocation.getFilename() +" using default"); 
      } 
     }else{ 
      logger.warn("Override location not set, using default settings"); 
     } 
    } 


    @Override 
    public void afterPropertiesSet() throws Exception { 
     setProperLocation(); 
    } 

然後,你需要定義bean作爲運行

<bean class="com.commons.config.EnvironmentalPlaceHolderConfigurer"> 
    <property name="overrideLocation" value="classpath:/jms/${ENV_NAME}-jms.properties" /> 
    <property name="location" value="classpath:/jms/jms.properties" /> 
</bean> 

您需要定義機器上的環境入口與主要爲「ENV_NAME」

例如:ENV_NAME = prod

在Windows環境變量的情況下以及在.profile中的unix條目的情況下。

您需要用以下方式 prod-jms.properties uat-jms.properties

2

維護每個環境屬性也許你正在尋找類似的@Value註解?

private @Value("#{connection.dev.url}") String myURL;