如何在Spring中加载系统属性文件?

Pol*_*878 8 java spring spring-mvc

我有一个属性文件,我想加载到系统属性,以便我可以通过它访问它System.getProperty("myProp").目前,我正试图<context:propert-placeholder/>像这样使用Spring :

<context:property-placeholder location="/WEB-INF/properties/webServerProperties.properties" />
Run Code Online (Sandbox Code Playgroud)

但是,当我试图通过System.getProperty("myProp")我获得我的属性null.我的属性文件如下所示:

myProp=hello world
Run Code Online (Sandbox Code Playgroud)

我怎么能实现这个目标?我很确定我可以设置运行时参数,但是我想避免这种情况.

谢谢!

小智 17

在Spring 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>
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 10

关键是要做到这一点 - 即使用弹簧中的系统属性,而不是系统中的弹簧属性.

随着PropertyPlaceholderConfigurer你通过访问你的属性+系统属性${property.key}语法.在Spring 3.0中,您可以使用@Value注释注入这些内容.

这个想法不是依赖于调用System.getProperty(..),而是依赖于注入属性值.所以:

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

public void someMethod {
    String path = getPath(foo);
    //.. etc
}
Run Code Online (Sandbox Code Playgroud)

而不是

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

想象一下,您想要对您的类进行单元测试 - 您必须System使用属性预填充对象.使用spring-way,你只需要设置对象的一些字段.


Sea*_*oyd 9

当我订阅Bozho精神的答案时,我最近还遇到了需要从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);
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

弹簧配置:

<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>
Run Code Online (Sandbox Code Playgroud)