【问题标题】:Profile specific custom property files in Spring boot在 Spring Boot 中配置特定的自定义属性文件
【发布时间】:2019-06-28 09:18:11
【问题描述】:

想检查 Spring boot 是否提供了使用除 application.properties 文件之外的配置文件的帮助。例如:my-custom.properties 文件,可以是特定配置文件, 例如:

  1. my-custom-dev.properties dev 个人资料
  2. my-custom-uat.properties uat 个人资料

编辑:问题是,我有正常的 application-{env}.property 文件,除此之外,还有其他属性文件根据它们的数据内容(例如:我想要的用于日志记录的 DB 特定属性存储在 `db-log.properties 中,如何使其他文件配置文件敏感?

【问题讨论】:

  • Spring Boot 参考指南中对here 进行了解释。简而言之,添加 --spring.config.name=application,file1,file2 这将指示 Spirng Boot(可选)检测默认值旁边的 file1.properties 和 `file1-{profile}.properties。

标签: java spring spring-boot spring-profiles


【解决方案1】:

是的。绝对地。您只需在开始时提供您想要的个人资料。
例如:

-Dspring.profiles.active=prod 

将使用 application-prod.properties

-Dspring.profiles.active=customer

将使用 application-custom.properties

【讨论】:

    【解决方案2】:

    除了 application.properties 文件,

    可以使用以下约定定义特定于配置文件的属性:application-{profile}.properties。

    环境有一组默认配置文件(默认情况下,[默认]),如果没有设置活动配置文件(换句话说,如果没有显式激活配置文件,则从 application-default.properties 加载属性) )

    运行多个配置文件:

    1.application-prod.properties

    2.application-dev.properties

    mvn spring-boot:run -Dspring-boot.run.profiles=dev,prod
    

    3.application.properties(默认配置文件)

    mvn spring-boot:run
    

    4.带有自定义属性文件的命令行参数

    spring.config.name - 设置配置文件名(逗号分隔值) spring.config.location - 设置 Spring Boot 将找到您的外部化配置文件的位置。

    java -jar hello-world.jar --spring.config.name=application,conf --spring.config.location=classpath:/external/properties/,classpath:/com/learn/../../
    

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

    【讨论】:

    • 当您以这种方式激活多个配置文件时,属性文件的顺序是否具有确定性(如果您为相同的属性提供不同的值)?
    【解决方案3】:

    除了application.properties 文件,您可以根据需要定义为application-{profile}.properties。 所选文件在启动时根据您选择的配置文件确定。

    【讨论】:

      【解决方案4】:

      spring 使用的默认约定是 application-.properties。因此,如果配置文件是 dev,那么它会查找 application-dev.properties

      您也可以使用 bootstrap.properties 文件并指定 spring.application.name=my-custom

      在这种情况下,spring 会查找 my-custom.properties 文件,当然你可以将它与配置文件 dev,uat 一起使用,因此属性文件名应该是 my-custom-dev.properties。

      您也可以将配置文件作为命令行参数传递 -Dspring.config.location=文件的路径。

      【讨论】:

        【解决方案5】:

        您可以将其与活动配置文件一起使用

        @Configuration
        @PropertySource("classpath:my-custom-${spring.profiles.active}.properties")
        

        【讨论】:

        • 这不会像您认为的那样起作用。 spring.profiles.active 是一个数组而不是单个元素。您可以一次启用多个配置文件。然后这将不起作用,因为它将查找名为 my-custom-[profile1,profile2].properties 的文件。我很难想象它是真正的名字。
        猜你喜欢
        • 2020-12-21
        • 2018-11-14
        • 1970-01-01
        • 2017-01-07
        • 2020-10-26
        • 2020-06-14
        • 2016-08-22
        • 2016-07-12
        • 1970-01-01
        相关资源
        最近更新 更多