【问题标题】:Overriding spring properties in application.properties that is part of a jar覆盖作为 jar 一部分的 application.properties 中的 spring 属性
【发布时间】:2016-09-13 22:20:08
【问题描述】:

我正在开发一个 Spring Boot 应用程序(我们称之为 MyLib)。它使用弹簧云流。这个想法是这个应用程序将被另一个java应用程序用作一个jar(我们称之为MyApp。它可能不是一个spring boot)。我想要做的是 MyApp 将指定 spring.cloud.stream.bindings.<channel>.destination 将由 MyLib 中的代码使用。

这可以实现吗?

【问题讨论】:

    标签: spring-boot jar spring-cloud


    【解决方案1】:

    从外部 jar 加载 application.properties

    我不知道 spring.cloud.stream.bindings 具体是什么,但是 Spring Boot 应用程序可以从多个位置加载其 application-${profile}.properties,包括类路径上的 jars:

    Spring Boot documentation:

    SpringApplication 将从 application.properties 加载属性 在以下位置创建文件并将它们添加到 Spring 环境:

    • 当前目录的 /config 子目录。
    • 当前目录
    • 类路径 /config 包
    • 类路径根

    列表按优先级排序(在位置定义的属性 列表中较高的位置会覆盖较低位置中定义的那些)。

    ...

    默认搜索路径 classpath:,classpath:/config,file:,file:config/ 总是被使用, 与spring.config.location的值无关

    换句话说,application-${profile}.properties 文件必须位于您的MyApp.jar 内的././config/

    您还可以使用spring.config.location 定义其他查找文件夹,但这必须在运行时完成:

    spring.config.namespring.config.location 很早就用于确定哪些文件 必须加载,因此必须将它们定义为环境 属性(通常是操作系统环境、系统属性或命令行参数)。


    查找顺序

    你提到 :

    覆盖 application.properties 中的 spring 属性

    考虑属性的顺序如下 (from spring documentation):

    • 您的测试中的@TestPropertySource 注释。
    • 命令行参数。
    • 来自 SPRING_APPLICATION_JSON 的属性(嵌入在环境变量或系统属性中的内联 JSON)
    • ServletConfig 初始化参数。
    • ServletContext 初始化参数。
    • 来自 java:comp/env 的 JNDI 属性。
    • Java 系统属性 (System.getProperties())。
    • 操作系统环境变量。
    • 仅具有随机属性的 RandomValuePropertySource。*。
    • 打包 jar 之外的特定于配置文件的应用程序属性(application-{profile}.properties 和 YAML 变体)
    • 打包在您的 jar 中的特定于配置文件的应用程序属性(application-{profile}.properties 和 YAML 变体)
    • 打包 jar 之外的应用程序属性(application.properties 和 YAML 变体)。
    • 应用程序属性打包在您的 jar 中(application.properties 和 YAML 变体)。
    • @Configuration 类上的@PropertySource 注释。
    • 默认属性(使用 SpringApplication.setDefaultProperties 指定)。

    【讨论】:

      猜你喜欢
      • 2020-06-22
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多