我正在处理一个项目,并且有一个用例,我需要从 JAR 外部为 Spring Boot 提供 application.properties 文件。
根据 Baeldung , 获取 application.properties 的优先顺序是
- 当前目录的/config 子目录
- 当前目录
- 类路径/配置包
- 类路径根
前两个的问题是我需要导航到包含运行 JAR 配置的目录。在本地工作时这听起来没问题,但在通过 CI/CD 框架部署到远程主机时,这不是一个可行的解决方案。
我试图找到一种使用类路径的机制,并避免使用 here 中提到的 spring boot 命令行选项或设置环境变量。
我无法弄清楚如何在运行 FAT JAR 时设置类路径并一起指定配置。如果可以,请帮我解决一下!
提前致谢:)
编辑:我知道有一些方法可以使用 Spring Boot 的命令行选项(例如 spring.config 或 loader.path 等)来实现这一点。
我试图找到一个基于类路径和目录结构的更隐式的解决方案,只是为了减少它与正在使用 Spring Boot 的事实的耦合。
最佳答案
根据Spring docs ,您可以使用 spring.config.location
属性定义外部配置位置。更具体地说:
If
spring.config.location
contains directories (as opposed to files), they should end in / (and, at runtime, be appended with the names generated fromspring.config.name
before being loaded, including profile-specific file names). Files specified inspring.config.location
are used as-is, with no support for profile-specific variants, and are overridden by any profile-specific properties.Config locations are searched in reverse order. By default, the configured locations are:
classpath:/,classpath:/config/,file:./,file:./config/.
The resulting search order is the following:
file:./config/ file:./ classpath:/config/ classpath:/
When custom config locations are configured by using
spring.config.location
, they replace the default locations. For example, ifspring.config.location
is configured with the value
classpath:/custom-config/,file:./custom-config/
the search order becomes the following:
file:./custom-config/ classpath:custom-config/
Alternatively, when custom config locations are configured by using
spring.config.additional-location
, they are used in addition to the default locations. Additional locations are searched before the default locations. For example, if additional locations ofclasspath:/custom-config/,file:./custom-config/
are configured, the search order becomes the following:
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
关于java - FAT JAR 外部的 Spring Boot 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61922876/