java - FAT JAR 外部的 Spring Boot 属性

标签 java spring spring-boot config executable-jar

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

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

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

前两个的问题是我需要导航到包含运行 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 from spring.config.name before being loaded, including profile-specific file names). Files specified in spring.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, if spring.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 of classpath:/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/

相关文章:

java - 如何使用 Spring 4 Autowiring 泛型类?

java - 注释验证很慢

jquery - 使用 'a href' 构建动态 URL

java - Spring 原型(prototype)引用 Singleton

java - 添加 @ComponentScan 从 jar 加载 bean 后,我的 Controller 未扫描,并且收到 404

java - Parcelable 在没有正确实现的情况下工作

java - 如何将此伪代码转换为 Java 而不会出现 java.lang.ArrayIndexOutOfBoundsException

Spring Boot 从 2.3.6.RELEASE 迁移到 2.4.0 和 json ClassCastException

java - 整数区间内的哈希表键

java - 为什么 Spring Boot 后端 JAR 文件在 Ubuntu 上只运行一小段时间?如何让它作为服务运行?