天天看點

Spring Boot 配置 yaml

學習 Spring Boot 項目中的配置檔案( yaml 格式),如: application.yaml 。

1 檔案位置

Spring Boot 項目中的配置檔案

application.yaml

最常見的位置在

src/main/resources

目錄下,其實共有 4 個預設位置能放,如下(優先級: 1 > 2 > 3 > 4 ):

  1. 項目根目錄下的 config 目錄下。
  2. 項目的根目錄下。
  3. classpath 目錄下的 config 目錄下。
  4. classpath 目錄下。

Spring Boot 啟動時,預設會從這 4 個位置按順序去查找相關屬性并加載,重複的屬性以優先級高的為準。

但并非絕對的,我們也可以自定義位置(如:

src/main/resources/cxy35/application.yaml

),并在項目啟動時通過

spring.config.location

屬性來手動的指定配置檔案的位置,指定方式如下:

  1. IntelliJ IDEA 中。
Spring Boot 配置 yaml
  1. 指令行中。
java -jar spring-boot-yaml-0.0.1-SNAPSHOT.jar --spring.config.location=classpath:/cxy35/
           

注意:通過

spring.config.location

屬性指定時,表示自己重新定義配置檔案的位置,項目啟動時就按照定義的位置去查找配置檔案,這種定義方式會覆寫掉預設的 4 個位置。另外可以通過

spring.config.additional-location

屬性來指定,表示在預設的 4 個位置的基礎上,再添加幾個位置,新添加的位置的優先級大于原本的位置。

2 檔案名

Spring Boot 項目中的配置檔案預設檔案名是

application.yaml

,與檔案位置類似,也可以自定義,比如叫

app.yaml

,并在項目啟動時通過

spring.config.name

屬性來手動的指定配置檔案的檔案名,如:

java -jar spring-boot-yaml-0.0.1-SNAPSHOT.jar --spring.config.name=app

當然,配置檔案的位置和檔案名可以同時自定義。

3 普通的屬性注入

首先在

application.yaml

配置檔案中定義屬性:

book:
  id: 1
  name: 三國演義
  author: 羅貫中
  editors:
    - 張三
    - 李四
  chapters:
    - id: 1
      name: 第一章 桃園結義
    - id: 2
      name: 第二章 除董卓
           

再定義一個 Book 和 Chapter 類,并通過

@Value

注解将這些屬性注入到 Book 對象中(注意: Book 對象必須要交給 Spring 容器去管理):

@Component
public class Book {
    @Value("${book.id}")
    private Long id;
    @Value("${book.name}")
    private String name;
    @Value("${book.author}")
    private String author;
    @Value("${book.editors}")
    private List<String> editors; // 普通數組/清單注入
    @Value("${book.chapters}")
    private List<Chapter> chapters; // 對象數組/清單注入

    // getter/setter
}
           
public class Chapter {
    private Long id;
    private String name;

    // getter/setter
}
           

因為

application.yaml

配置檔案會被自動加載,是以上述屬性可以注入成功,可通過在 controller 或者單元測試中注入 Book 對象來測試。

yaml 配置目前不支援

@PropertySource

注解。

上述方式在 Spring 中也可以使用,和 Spring Boot 沒有關系。

4 類型安全的屬性注入(推薦)

當配置的屬性非常多的時候,上述方式工作量大且容易出錯,是以就不合适了。在 Spring Boot 中引入了類型安全的屬性注入,通過

@ConfigurationProperties

注解來實作,如下:

@Component
@ConfigurationProperties(prefix = "book")
public class Book {
    private Long id;
    private String name;
    private String author;
    private List<String> editors; // 普通數組/清單注入
    private List<Chapter> chapters; // 對象數組/清單注入

    // getter/setter
}
           

5 properties 與 yaml 配置的差別

  1. properties 配置無序,yaml 配置有序。在有些配置中順序是非常有用的,例如 Spring Cloud Zuul 的配置。
  2. yaml 配置目前不支援

    @PropertySource

    注解。
  • Spring Boot 教程合集(微信左下方閱讀全文可直達)。
  • Spring Boot 教程合集示例代碼:https://github.com/cxy35/spring-boot-samples
  • 本文示例代碼:https://github.com/cxy35/spring-boot-samples/tree/master/spring-boot-yaml

掃碼關注微信公衆号 程式員35 ,擷取最新技術幹貨,暢聊 #程式員的35,35的程式員# 。獨立站點:https://cxy35.com

Spring Boot 配置 yaml

繼續閱讀