2010-11-07 60 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> 
相关问题