【问题标题】:Spring boot application.properties extends another property fileSpring boot application.properties 扩展了另一个属性文件
【发布时间】:2016-01-20 16:28:39
【问题描述】:

我想继承到应用程序属性的一个属性文件中的属性很少。请让我们知道这在 Spring Boot 中是否可行。

类似

application.properties
----------------------
extends = otherproperty.properties
property1 = value1
property2= value2
property3 = value3

otherproperty.properties
------------------------
property4=value4
property5 = value5

当 spring boot 应用程序加载时,我希望所有 5 个属性都应该加载并使用 @Value 注释可用。 Spring Boot 会自动选择类路径中的 application.properties,我没有 applicaitoncontext xml 或任何属性加载器代码。

提前致谢。

【问题讨论】:

  • 您想继承一个属性文件到另一个,还是想合并它们?也就是说,两个属性文件可以包含属性property6,还是不重叠?
  • 我只是想继承,他们不重叠。
  • 如果属性重叠会发生什么? application.properties 中的属性值会被其他 property.properties 覆盖吗?

标签: spring spring-boot


【解决方案1】:

您可以为此使用个人资料

使用application.properties 文件,您可以为每个Profile 定义一个文件,如下所示:

application.properties # This is the main file
spring.profiles=p1,p2,p3
prop-main=hi

application-p1.properties # This is the file with p1 properties
property1=patata

application-p2.properties # This is the file with p2 properties
property2=catsup

application-p3.properties # This is the file with p3 properties
property3=helloworld

Spring 将翻译文件并像这样使用它:

application.properties # This is the main file
spring.profiles=p1,p2,p3
prop-main=hi
property1=patata
property2=catsup
property3=helloworld

此解决方案有效,但您必须为每个组保留一个单独的文件。

还有另一种方法,您可以使用单个YAML 文件而不是多个properties 文件。只需将 application.properties 替换为 application.yml 并执行以下操作:

server:
    address: 192.168.1.100
---
spring:
    profiles: development
server:
    address: 127.0.0.1
---
spring:
    profiles: production
server:
    address: 192.168.1.120

您可以阅读参考文档以获取有关 Using YAML instead of PropertiesMulti-profile YAML documents 的更多信息。

【讨论】:

    【解决方案2】:

    对我来说,spring.profiles.include=p1,p2,p3application.properties 文件中工作

    【讨论】:

    • spring.profiles.include 也可以在 application-dev.properties 中工作吗?假设我有两个开发环境 dev1 和 dev2,它们有许多共同的属性。我想要一个 devbase.properties 我想包含在 dev1 和 dev2 中这可能吗?
    【解决方案3】:

    我有同样的问题,并通过 mkyong 找到了一个很好的解释解决方案。本教程解释了如何通过使用 .porperties.yaml 文件来使用不同的扩展 Spring 配置文件。 (与eSala 提到的方法相同。)

    https://www.mkyong.com/spring-boot/spring-boot-profile-based-properties-and-yaml-example/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 2018-09-27
      • 2015-03-13
      • 1970-01-01
      • 2020-06-22
      • 2021-05-17
      • 2015-01-12
      相关资源
      最近更新 更多