开发Spring应用程序时,最常见的用例是您希望拥有多个版本的配置属性,具体取决于要部署到的位置,例如,数据库URL或功能标志可能是特定于dev,qa,production等环境的。
像大多数Spring开发任务一样,有多种方法可以解决问题。 我的偏好基于以下假设和偏好:
- 我们创建一个默认的配置属性文件(例如“ appConfig.properties”),并将其打包在可部署工件(JAR或WAR等)中
- 该文件将包含一组合理的默认“基线”属性,应用程序需要这些属性才能成功运行
- 我们要通过位于已部署应用程序的工作目录中的外部文件覆盖基准appConfig.properties文件中的属性
- 我们通常将此文件命名为appConfigOverride.properties
- 在执行应用程序或设置系统变量时,可以通过在命令行上传递参数来覆盖应用程序属性,但这是一个单独的主题
解决方案
我们为application-context.xml使用以下结构:
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="file:appConfigOverride.properties" order="-1"ignore-unresolvable="true" ignore-resource-not-found="true" /><context:property-placeholder location="classpath:appConfig.properties" />....</beans>
这里的关键是'order'属性,当在另一个文件中也找到该属性(有效覆盖另一个文件中的值)时,该属性将强制使用在appConfigOverride.properties中找到的属性,以及'ignore-unresolvable = “ true” ignore-resource-not-found =“ true”'允许Spring在找不到外部文件(或不包含覆盖appConfig文件的所有默认属性)的情况下继续加载上下文
参考: The Tai-Dev Blog博客上的JCG合作伙伴 Daniel Bryant 通过外部文件覆盖打包的Spring应用程序属性文件 。
翻译自: https://www.javacodegeeks.com/2013/07/overriding-a-packaged-spring-application-properties-file-via-an-external-file.html