2010-11-07 59 views
8

我有一個屬性文件,我想加載到系統屬性,以便我可以通過System.getProperty("myProp")訪問它。目前,我正在嘗試使用Spring <context:propert-placeholder/>像這樣:如何在Spring中加載系統屬性文件?

<context:property-placeholder location="/WEB-INF/properties/webServerProperties.properties" /> 

然而,當我嘗試通過System.getProperty("myProp")我越來越null訪問我的屬性。我的屬性文件看起來像這樣:

myProp=hello world 

我怎麼能做到這一點?我很確定我可以設置運行時參數,但是我想避免這種情況。

謝謝!

+0

也許[這個相關的問題(http://stackoverflow.com/questions/1311360/property-placeholder-location-from-another-property)給出了一些方向? – Raghuram 2010-11-07 06:12:17

回答

9

雖然我訂閱了Bozho's answer的精神,但我最近也遇到了需要從Spring設置系統屬性的情況。這是我想出了類:

Java代碼:

public class SystemPropertiesReader{ 

    private Collection<Resource> resources; 

    public void setResources(final Collection<Resource> resources){ 
     this.resources = resources; 
    } 

    public void setResource(final Resource resource){ 
     resources = Collections.singleton(resource); 
    } 

    @PostConstruct 
    public void applyProperties() throws Exception{ 
     final Properties systemProperties = System.getProperties(); 
     for(final Resource resource : resources){ 
      final InputStream inputStream = resource.getInputStream(); 
      try{ 
       systemProperties.load(inputStream); 
      } finally{ 
       // Guava 
       Closeables.closeQuietly(inputStream); 
      } 
     } 
    } 

} 

Spring配置:

<bean class="x.y.SystemPropertiesReader"> 

    <!-- either a single .properties file --> 
    <property name="resource" value="classpath:dummy.properties" /> 

    <!-- or a collection of .properties file --> 
    <property name="resources" value="classpath*:many.properties" /> 

    <!-- but not both --> 

</bean> 
10

重點是以相反的方式做到這一點 - 即在春季使用系統屬性,而不是系統中的彈簧屬性。

藉助PropertyPlaceholderConfigurer,您可以通過${property.key}語法獲得您的屬性+系統屬性。在3.0版本中,您可以使用@Value註釋注入這些文件。

這個想法不是依靠調用System.getProperty(..),而是要注入您的屬性值。所以:

@Value("${foo.property}") 
private String foo; 

public void someMethod { 
    String path = getPath(foo); 
    //.. etc 
} 

而不是

public void someMethod { 
    String path = getPath(System.getProperty("your.property")); 
    //.. etc 
} 

假如你想進行單元測試你的類 - 你必須與預填充屬性System對象。隨着春天的方式,你只需設置對象的一些領域。

+0

是否還有一種方法以編程方式獲取屬性,而不是使用Spring表達式語法的註釋?例如:'someSpringApi.getProperty(「$ {foo.property}」)' – Polaris878 2010-11-07 15:57:17

+0

是 - http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch07 html的 – Bozho 2010-11-07 16:27:57

17

在春季3,你可以加載系統屬性是這樣的:

<bean id="systemPropertiesLoader" 
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
    <property name="targetObject" value="#{@systemProperties}" /> 
    <property name="targetMethod" value="putAll" /> 
    <property name="arguments"> 
     <util:properties location="file:///${user.home}/mySystemEnv.properties" /> 
    </property> 
</bean> 
相關問題