SpringBoot2.x基礎篇:使用YAML代替Properties的對應配置

  • 2020 年 3 月 27 日
  • 筆記

普通配置

普通的方式比較簡單直接,不存在數組集合子類等相關配置,我們通過Properties方式編寫了如下的配置內容:

system.config.max-value=100  system.config.min-value=10  system.config.location=classpath:/configs

那這種方式對應的YAML配置是什麼樣子的呢?

如下所示:

system:    config:      min-value: 10      max-value: 100      location: classpath:/configs

這兩種方式對比之下,YAML層次感鮮明,更直觀的查看配置資訊,而Properties這種方式配置前綴相對來說是冗餘的,如果配置前綴過長,每一行的配置內容則會更長。

List配置

如果你需要添加List/Set/Array類型的配置資訊,使用Properties方式編寫如下所示:

system.config.ports[0]=8080  system.config.ports[1]=8081  system.config.ports[2]=8082

注意事項:配置的索引從0開始。

對應上面配置的YAML實現如下所示:

system:    config:      ports:        - 8080        - 8081        - 8082

無論是Properties還是YAML格式,這種List的配置內容都可以通過如下的方式獲取:

@Configuration  @ConfigurationProperties(prefix = "system.config")  @Data  public class LoadListConfig {      private List<String> ports;  }

List內實體配置

如果你的List內不是基本數據類型,而是一個實體類,使用Properties的配置方式如下所示:

system.users[0].username=admin  system.users[0][email protected]  system.users[1].username=hengboy  system.users[1][email protected]

其實跟上面的List配置差不多,不過如果你需要配置每一個索引內欄位的值,就要一一指定配置值。

對應上面的YAML實現如下所示:

system:    users:      - username: admin        email: [email protected]      - username: hengboy        email: [email protected]

每一個 - 其實代表集合內的一個元素。

獲取List實體配置時我們可以通過如下的方式:

@Data  @Configuration  @ConfigurationProperties(prefix = "system")  public class LoadSystemUserConfig {      private List<User> users;        @Getter      @Setter      public static class User {          private String username;          private String email;      }  }

YAML缺點

一種方案的誕生是為了解決相應的問題,雖然說存在既有道理,但是每一種方案也不是完美的都有自身的缺點。

下面簡單說說YAML的缺點:

  • 配置時縮進要特別注意,如果存在空格縮進對應不齊就會出現問題
  • SpringBoot內無法通過@PropertySource註解載入YAML文件。