【问题标题】:Spring boot Loading multiple properties filesSpring boot 加载多个属性文件
【发布时间】:2019-03-30 20:26:06
【问题描述】:

我有一个 application.properties,它指定要加载到应用程序中的属性文件的名称。

application.properties

sources=a_source,b_source,c_source

a_source、b_source 和 c_source 具有相同的变量。

a_source.properties

location = locationb

b_source.properties

location = locationb

c_source.properties

location=locationc

因此,如果我将属性文件的名称添加到 application.properties 中,例如 d_source,那么 d_source.properties 应该由应用程序自动加载。这样我的应用程序就可以处理来自 4 个属性文件的数据。这在 Spring Boot 中是否可行?

【问题讨论】:

  • 为什么需要多个属性文件?

标签: java spring spring-boot properties properties-file


【解决方案1】:

如果您试图将多个应用程序属性视为多个 java 属性资源,那么您就大错特错了。你不能也不应该。每个应用程序为每个环境/配置文件定义一个属性/yaml 文件。

但是,如果您想将 application.properties 或 yaml 视为环境/配置文件的基础,您可以执行以下操作:

例如,

application-integration_test.yaml:

spring.profiles: integration_test
spring.profiles.include:
  - unit_test
  - mock_test

在上面的一个中,您所说的是每当您拥有“integration_test”的活动配置文件时,还包括来自“unit_test”和“mock_test”配置文件的配置。

但请注意,如果任何相同或重复的属性或配置键 在包含的配置文件中定义,属性值被覆盖并且 替换为下一个提到的配置文件。在这种情况下,如果您有相同的 在所有 3 个配置文件中具有不同值的属性键,mock_test 配置文件的值用作最终值。

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

【讨论】:

    【解决方案2】:

    也许您应该考虑使用配置文件。看一下这个: Profiles Profile Specific Properties

    【讨论】:

    • 但一次只能为应用程序激活一个配置文件,对吧?
    【解决方案3】:

    您也可以使用此解决方案:

    application-unit_test.properties

    # content of file
    

    application-mock_test.properties

    # content of file
    

    application.properties

    spring.profile.active = default
    spring.profiles.include = unit_test, mock_test
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2018-03-28
      • 2017-11-17
      • 2016-10-24
      • 2016-06-18
      • 2017-08-18
      • 2014-12-21
      • 2020-04-14
      • 2015-01-16
      相关资源
      最近更新 更多