【问题标题】:Spring Boot Properties Outside FAT JARFAT JAR 外的 Spring Boot 属性
【发布时间】:2020-09-07 09:31:15
【问题描述】:

我正在处理一个项目并且有一个用例,我需要从 JAR 外部为 Spring Boot 提供 application.properties 文件。

根据Baeldung,获取application.properties的优先顺序是

  1. 当前目录的 /config 子目录
  2. 当前目录
  3. 类路径 /config 包
  4. 类路径根

前两个的问题是我需要导航到包含配置的目录才能运行 JAR。在本地工作时听起来没有问题,但在通过 CI/CD 框架部署在远程主机上时,这不是一个可行的解决方案。

我正在尝试使用类路径找到一种机制,并避免使用 here 中提到的 Spring Boot 命令行选项或设置环境变量。

我无法弄清楚如何在运行 FAT JAR 时设置类路径并一起指定配置。如果可以的话,请帮我弄清楚!

提前谢谢:)

编辑:我知道有一些方法可以使用 Spring Boot 的命令行选项来实现这一点,例如 spring.config 或 loader.path 等。

我试图找到一个基于类路径和目录结构的更隐含的解决方案,只是为了减少它与正在使用 Spring Boot 的事实的耦合。

【问题讨论】:

  • 你试过用java -jar app.jar --spring.config.location=another-location.properties
  • 嘿,我希望直接使用类路径,而不必使用提供的 Spring Boot 运行时选项,例如 spring.config、loader.config 等。只需 JAR、属性文件和类路径,指定 JAR 和配置所需的位置. (最后 2 个优先选项)

标签: java spring spring-boot config executable-jar


【解决方案1】:

根据Spring docs,您可以使用spring.config.location 属性定义外部配置位置。更具体地说:

如果spring.config.location 包含目录(而不是文件), 它们应该以 / 结尾(并且在运行时附加名称 在被加载之前从spring.config.name 生成,包括 配置文件特定的文件名)。 中指定的文件 spring.config.location 按原样使用,不支持 配置文件特定的变体,并被任何配置文件特定的变体覆盖 属性。

以相反的顺序搜索配置位置。默认情况下, 配置的位置是:

classpath:/,classpath:/config/,file:./,file:./config/.

结果 搜索顺序如下:

file:./config/ file:./ classpath:/config/ classpath:/

自定义时 配置位置是使用spring.config.location 配置的,它们 替换默认位置。例如,如果spring.config.location 配置了值

classpath:/custom-config/,file:./custom-config/ 搜索顺序 变成如下:

file:./custom-config/ classpath:custom-config/

或者,当 自定义配置位置是通过使用配置的 spring.config.additional-location,除了 默认位置。 在 默认位置。例如,如果其他位置 classpath:/custom-config/,file:./custom-config/ 被配置, 搜索顺序变为如下:

file:./custom-config/ classpath:custom-config/ file:./config/ file:./ classpath:/config/ classpath:/

包含您的外部配置的目录的示例用法如下:

java -jar myproject.jar --spring.config.location=file:/custom-config-dir/

或者直接到外部配置文件:

java -jar myproject.jar --spring.config.location=file:/custom-config-dir/custom-config.properties

【讨论】:

  • 嘿,我很欣赏这个答案,但我们试图在不使用 spring 提供的运行时选项的情况下实现它。我添加了一个 EDIT 来提问。你知道与此一致的方法吗?
【解决方案2】:

将自定义配置位置指定为 VM 参数是另一种选择。

java -Dspring.config.location=<config-dir-path> -jar demo.jar

【讨论】:

  • 此线程上的更多选项。 stackoverflow.com/questions/39716796/…
  • 感谢您的回答,但我们正在尝试在不使用 spring 提供的运行时选项的情况下实现它。我添加了一个 EDIT 来提问。你知道与此一致的方法吗?
  • spring 提供的运行时选项是什么意思。你的意思是喜欢通过休息服务之类的东西来使用它。您想在应用运行时更改运行时的属性?
  • 我的意思是弹簧启动运行时选项来设置 spring.config , loader.path 等我只想使用类路径和 jar
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2019-06-12
  • 2021-06-03
  • 2021-02-27
  • 2015-04-16
  • 2017-06-21
  • 2017-06-18
相关资源
最近更新 更多