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

新手上路,请多包涵

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

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

但是,当我尝试通过 System.getProperty("myProp") 访问我的属性时,我得到了 null 。我的属性文件如下所示:

 myProp=hello world

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

谢谢!

原文由 Polaris878 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 483
2 个回答

虽然我订阅了 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);
            }
        }
    }

}

弹簧配置:

 <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>

原文由 Sean Patrick Floyd 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 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>

原文由 Florin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题