2011-03-04 92 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;