Spring Boot中配置文件的默认值

时间:2018-10-08 05:18:10

标签: spring spring-boot

我有多个配置文件,并且有很多属性(将会增长),我不想每次都在不同的配置文件中设置每个属性。

我有一个 application.yml 文件,如下所示:

  freemarker:
    template-loader-path: classpath:/templates

  datasource:
    username: postgres
    password: mypass
    driver-class-name: org.postgresql.Driver

  jpa:
    show-sql: true
    properties:
      hibernate:
        jdbc:
          lob:
            non_contextual_creation: true
        dialect: org.hibernate.dialect.PostgreSQLDialect
    hibernate:
      ddl-auto: create

  security:
    secret: "jwt_secret_key_it_is_a_random_key_229"
    loginTokenExpiration: 86400
    confirmUserTokenExpiration: 86400
    devTokenExpiration: 157680000
    tokenPrefix: "Bearer"
    headerString: "Authorization"
    signUpUrl: "/token/login"

mysite:
  apiTosUrl: "https://example.com/api-tos"
  fromEmail: "alert@example.com"
  firstFreeCredits: 10

junction:
  port: 9080
  hasBasicAuth: false

---

spring:
  profiles:
    active: dev

---

spring:
  profiles: stage

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

chargeBee:
  site: "example.chargebee.com"
  apiKey: "mykey"

---

spring:
  profiles: prod

  datasource:
    url: jdbc:postgresql://localhost/myproddb

  jpa:
    show-sql: false
    hibernate:
      ddl-auto: update

chargeBee:
  site: "example.chargebee.com"
  apiKey: "myapikey"

大多数设置在配置文件之间是通用的,而并非通用的,我已经在配置文件的相应部分中对其进行了重新定义。 我假设此YAML文档的第一部分用默认值填充属性,而相应的部分将其覆盖。

这种方法正确吗?如果不是,那么如何继承属性值,这样我就可以一次定义公共值,而对于其他配置文件,我只需要定义不同的值?

2 个答案:

答案 0 :(得分:1)

是正确的方法来定义多个配置文件

  

您可以在一个文件中指定多个特定于配置文件的YAML文档   使用spring.profiles键指示文件何时显示   适用,如以下示例所示:

请参阅官方文档24.6.3 Multi-profile YAML Documents

在下面的示例中,如果开发配置文件处于活动状态,则server.address属性为127.0.0.1.。同样,如果生产配置文件处于活动状态,则server.address属性为192.168.1.120。如果未启用developmentproduction配置文件,则该属性的值为192.168.1.100

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

答案 1 :(得分:1)

您还可以使用创建其他特定于配置文件的yml文件来获取配置文件。

还可以使用以下命名约定来定义您:

application-{profile}.yml

创建application.yml文件。该文件首先加载。加载application.yml文件的所有属性。

检查找到的任何活动配置文件(是stage),然后在成功加载默认配置文件后加载,然后加载application-stage.yml文件并覆盖现有属性并添加新属性。

spring:
  profiles:
    active: stage
    datasource:
      url: jdbc:postgresql://localhost:5432/springbootdb

application-stage.yml的相同位置创建application.yml文件。

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

chargeBee:
  site: "example.chargebee.com"
  apiKey: "mykey"

application-prod.yml的相同位置创建application.yml文件。

spring:
  datasource:
    url: jdbc:postgresql://localhost/myproddb

  jpa:
    show-sql: false
    hibernate:
      ddl-auto: update

chargeBee:
  site: "example.chargebee.com"
  apiKey: "myapikey"
相关问题