在 spring boot 2.4.0 版本中包含配置文件

Including profiles in spring boot 2.4.0 version

作为开发人员,我在本地开发环境中使用默认的 dev 配置文件。这是我的 application-dev.properties 文件的一部分:

# Profiles    
spring.profiles.include=auth

之前我使用 Spring Boot 2.3。0.RELEASE 并且 spring.profiles.include 属性 在运行时包含 auth 配置文件。

但是在我迁移到 Spring Boot 2.4.0 之后,我没有启用 auth 配置文件。 spring.profiles.include 属性 好像不像以前那样工作了。

请告诉我如何配置我的配置文件,以便获得与迁移前相同的结果。 (我不想在这里使用配置文件组)

提前致谢!

如果您的配置处理以不兼容的方式更改并且您希望使用“传统”处理方式,您可以通过设置重新启用它:

spring.config.use-legacy-processing=true

或者,使用 YAML:

spring:
  config:
    use-legacy-processing: true

这应该将配置处理恢复到 2.3.x 等效。但是请注意,这个 属性 的存在只是为了简化配置文件配置从 2.3.x2.4.x 的迁移,并且可能会在未来的主要版本中被弃用和删除 1,因此您仍应尽快尝试迁移。要了解此更改的原因和一些其他信息,请继续阅读。

2.4.0 中值得注意的是以下两个范例:

So in Spring Boot 2.4 we’re planning to make two significant changes to the way the properties and YAML files are loaded:

  1. Documents will be loaded in the order that they’re defined.

  2. Profiles can no longer be activated from profile specific documents.

此更改实际上使什么-覆盖-什么-何时逻辑变得更容易理解,但导致必须禁用某些功能。例如:

my.prop: test

---
spring.profiles: prodprops
my.prop: prod

---
spring.profiles: prod
# no longer works - activating a profile from a profile-specific document!
spring.profiles.include: prodprops
  

将导致异常,因为配置会尝试从特定于配置文件的文档中激活配置文件,这已不再被允许。

为了涵盖此用例(和其他用例),配置文件组 已添加为一项功能。这意味着要启用您以前的行为,您需要创建一个配置文件组,如下所示:

spring.profiles.group.<group>=dev, auth

或者,在 YAML 中:

spring:
  profiles:
    group:
      <group>: dev, auth

其中 <group> 是您选择的配置文件组的名称。请注意,您可以定义多个组,所有组都应具有不同的名称。如果您随后使用 <group> 配置文件启动您的应用程序,则应激活属于该组的所有配置文件。

作为旁注,Spring Boot 2.4.0 额外添加了对多文档 properties 文件的支持,如下所示:

test=value
spring.profiles.active=local
#---
spring.config.activate.on-profile=dev
test=overridden value

注意文档分隔符 (#---)。这允许您在 .properties 文件中具有与 .yml 文件中类似的覆盖逻辑。

同样,相关 update post 中提供了此信息和其他信息。

1 如果之前的弃用是任何指标,则 属性 应该最早在 2.5.0 或最晚 2.6.0 中删除,后者更有可能(并且从 2.5.x 开始弃用)。

您还可以使用 spring.config.import 根据此文档从其他文件导入配置 Config file processing in Spring Boot 2.4

您可以使用 spring.config.import 使用 classpath:

spring.config.import=classpath:application-DEV.yml,classpath:application-auth.yml

虽然我们上面有一个可以接受的答案。但我会通过多个文件分享我的解决方案。 我的项目中有多个配置文件

./
application.yml
application-auth.yml
application-mockauth.yml
application-datasource.yml

application-auth.yml 或 application-datasource.yml 的主体与我们在 spring boot 2.4 之前实现的相同。小幅调整将位于 application.yml

spring:
  profiles:
    group:
      "dev": "datasource,mockauth"
      "prod": "datasource,auth"

而不是 spring.profiles.include,您将使用环境名称(dev、prod...)对相关配置进行分组。