SpringBoot配置文件格式

122 阅读1分钟

配置文件是我们熟悉一个项目必须读懂的知识,在springboot项目中的配置文件通常是 yml格式 和 properties格式,这两种格式分别有什么特点呢?

传统 properties

spring.cloud.gateway.discovery.locator.enabled= true 
spring.cloud.gateway.routes[0].id= api-web-c
spring.cloud.gateway.routes[0].uri= lb://api
spring.cloud.gateway.routes[0].predicates[0]= Path=/api-web/**
spring.cloud.gateway.routes[0].predicates[1]= Cookie=token, 123456
spring.cloud.gateway.routes[0].filters[0]= StripPrefix=1

如上示例,如果很多配置属于同一类,那么它们都有相同的前缀,比较冗余。

yml格式

yml看起来更直观,类似JSON

spring:
  cloud:
    gateway:
      routes:
      - id: api-web-c
        uri: lb://api
        predicates:
            - Path=/api-web/**
            - Cookie=token, 123456
        filters:
            - StripPrefix=1
      - id: weight_low
        uri: https://weightlow.org
        predicates:
            - Weight=group1, 2

这样虽然更直观,但有一些需要理解的新语法,例如 - 代表什么?

yml格式解释

  1. 复杂数据类型,例如数组和集合
person:
    hobby:
        - play
        - read
        - sleep
或者
person:
    hobby:
        play,
        read,
        sleep
或者如下方式,推荐使用该方式,[]也可以省略
person:
    hobby: [play,read,sleep] 
  1. map集合
person:
    map:
        k1: v1
        k2: v2
#或者使用行内方式		
person:
    map: {k1: v1,k2: v2}