【问题标题】:Default and user-supplied property files w/ Spring带有 Spring 的默认和用户提供的属性文件
【发布时间】:2026-02-04 15:20:06
【问题描述】:

我想允许我的 Spring 3.1.2 应用程序从嵌入在我的 jar 中的默认属性文件加载配置属性,另外还允许用户将覆盖属性文件的路径指定为命令行参数。

我知道我可以将 <context:property-placeholder> 用于从我的类路径加载属性的简单场景,但我如何处理上述场景中的属性可能来自两个合并的属性文件?

我试图复制的场景基本上是由 Apache Commons Configuration 的 CompositeConfiguration 解决的。

【问题讨论】:

    标签: java spring configuration properties-file


    【解决方案1】:

    您可以通过系统属性添加属性文件名

    检查一下

    how to read System environment variable in Spring applicationContext

    http://www.summa-tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring/

    http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html#expressions-beandef-xml-based

    http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html

    UPD

    1 .第一种方法是将 PSPC 声明为

          <context:property-placeholder 
             location="classpath:app.properties, classpath:user.properties"
             ignore-resource-not-found="true" />
    

    然后你将你的 app.properties 包含到 jar 中。

    用户在类路径中包含(或不包含)包含 user.properties 的文件夹。

    user.properties 优先于 app.properties。

    2 。如果您需要用户指定确切的文件

        <context:property-placeholder
        location="classpath:app.properties, file:${userPropsPath}"
        ignore-resource-not-found="true" />
    

    用户添加-DuserPropsPath="&lt;full path here&gt;"


    这两种情况都可以使用 spring-3.1.1 进行测试。

    【讨论】:

    • 感谢您的回答,但缺少一个重要元素 - 如何将两个属性文件(一个作为应用程序的参数提供,另一个在资源中提供默认值)合并或视为复合的?我试图复制的场景基本上是由 Apache Commons Configuration 的 CompositeConfiguration 解决的。
    • 我周末没有工作,所以这是我第一次有机会查看您最出色的答案。正是我想要的。谢谢!