代码之家  ›  专栏  ›  技术社区  ›  DigitalZebra

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

  •  8
  • DigitalZebra  · 技术社区  · 15 年前

    System.getProperty("myProp") . 现在,我想用弹簧 <context:propert-placeholder/> 就像这样:

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

    但是,当我试图通过 System.getProperty(“myProp”) 我得到了 null

    myProp=hello world
    

    我怎么能做到这一点?我很确定我可以设置一个运行时参数,但我想避免这一点。

    谢谢!

    3 回复  |  直到 15 年前
        1
  •  9
  •   Community Mohan Dere    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);
                }
            }
        }
    
    }
    

    弹簧配置:

    <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>
    
        2
  •  17
  •   Florin    14 年前

    在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>
    
        3
  •  10
  •   Brian Agnew    15 年前

    关键是要用另一种方法来实现这一点,即在spring中使用系统属性,而不是在系统中使用spring属性。

    与 PropertyPlaceholderConfigurer 您可以通过 ${property.key} 语法。在Spring3.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