1. 程式人生 > >SpringBoot進擊 | 二淺出:Spring Boot配置詳解

SpringBoot進擊 | 二淺出:Spring Boot配置詳解


1.前言

上一節:SpringBoot進擊 | 一淺出:Spring Boot簡單快速上手書

上一篇介紹了 Spring Boot 的入門,在一般情況下,我們不需要做太多的配置就能夠讓 Spring Boot 正常執行。因為其使用“習慣優於配置”(專案中存在大量的配置,此外還內建了一個習慣性的配置,讓你無需手動進行配置)的理念可以讓我們的專案快速執行起來。 但是,我們還是需要有專案的,或者自己的屬性配置。

 

2.進擊

2.1.自定義屬性

當我們建立完一個 Spring Boot 專案的時候,會發現,系統預設給我們在專案的 src/main/java/resources 目錄下建立了一個application.properties。這就是我們這章要講的檔案。 

因為 YML 是 Spring Boot 的一個重要特性,所以,這裡我會將 application.properties 修改為 application.yml 。但是兩種檔案格式 Spring Boot 都支援,只是語法上,資料結構上有所不同。

2.1.1.自定義一組屬性

在 application.yml 中自定義一組屬性及其值:

server:
  port: 8000
wei:
  name_cn: 測試

2.1.2.讀取配置(通過 @Value(“${屬性名}”) 來讀取配置檔案的值

自定義屬性配置好後,在需要讀取的地方直接使用註解 @Value(“${屬性名}”) 進行屬性繫結和讀取。

package com.wei.controller.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 註解@RestController,相當於@Controller和@ResponseBody兩個註解的結合,使用這個註解的類裡面的方法都以json格式輸出
 */
@RestController
public class DemoController {

    @Value("${wei.name_cn}")
    private String name_cn;

    @Value("${server.port}")
    private String port;

    @RequestMapping(value = "/demo/hi")
    public String getDemoHi() {
        String result = "Hello, Spring Boot! 我是" + name_cn + ",埠:" + port;
        System.out.println(result);
        return result;
    }

}

執行程式啟動類,瀏覽器訪問URL:http://localhost:8000/demo/hi

我們可以看到瀏覽器顯示:

Hello, Spring Boot! 我是測試,埠:8000

 

2.2.自定義配置檔案

有時候我們並不希望把所有配置項都放在 application.yml 裡面,這時候我們可以另外自定義一個,比如 application-user.yml。

有時候我們有很多配置屬性,這時我們會把這些屬性作為欄位來建立一個Java Bean,並將屬性值賦給他們。

2.2.1.自定義一組屬性

新建自定義配置檔案 application-user.yml ,並定義以下屬性:

wei:
  name_cn: 測試
  name_en: SpringBoot-Tester
  age: ${random.int[1,300]}
  user_id: ${random.int}
  desc: Dear All, name:${name_en}, user_id:${user_id}, age:${age}
  • 屬性間引用:

配置檔案中的各個屬性之間也可以直接引用來使用,比如屬性desc

  • 隨機值配置:

配置檔案中的 ${random} 可以用來生成各種不同型別的隨機值,簡化程式碼生成的麻煩,比如生成 int 值,long 值,或者 string 字串。

2.2.2.讀取配置(將配置檔案的屬性賦給實體類來讀取配置檔案的值 

新建一個Javabean類,其屬性與 application-user.yml 中的屬性相互對應。當然,也可以使用 @Value("${desc}") 註解一個別名。如下:

package com.wei.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 註解@ConfigurationProperties,並加上它的prrfix,來指明使用哪個配置
 * 註解@PropertySource,引入自定義配置檔案
 */
@Component
@Configuration
@PropertySource(value = "classpath:application-user.yml")
@ConfigurationProperties(prefix = "wei")
public class DemoUserBean {

    @Value("${name_cn}")
    private String nameCn;
    @Value("${age}")
    private int age;
    @Value("${user_id}")
    private int userId;
    @Value("${desc}")
    private String description;

    public String getNameCn() {
        return nameCn;
    }

    public void setNameCn(String nameCn) {
        this.nameCn = nameCn;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

這裡需要加註解@ConfigurationProperties,並加上它的prrfix,來指明使用哪個配置。加註解@PropertySource,來引入我們自定義的配置檔案 application-user.yml。

2.2.3.新增核心依賴

pom.xml 依賴中新增一個核心依賴開啟註解@ConfigurationProperties

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

官方對 spring-boot-configuration-processor 的說明:

通過使用spring-boot-configuration-processor jar, 你可以從被@ConfigurationProperties註解的節點輕鬆的產生自己的配置元資料檔案。該jar包含一個在你的專案編譯時會被呼叫的Java註解處理器。想要使用該處理器,你只需簡單新增spring-boot-configuration-processor依賴。

2.2.4.在Controller類中引入ConfigBean

註解@EnableConfigurationProperties,指明要載入哪個bean。否則 @Autowired DemoUserBean 不能進行自動裝載。

package com.wei.controller.demo;

import com.wei.model.DemoUserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 註解@RestController,相當於@Controller和@ResponseBody兩個註解的結合,使用這個註解的類裡面的方法都以json格式輸出
 * 註解@EnableConfigurationProperties,指明要載入哪個bean
 */
@RestController
@EnableConfigurationProperties({DemoUserBean.class})
public class DemoUserController {

    @Autowired
    private DemoUserBean demoUserBean;

    @RequestMapping(value = "/demo/user/hi")
    public String getDemoHi() {
        String result = "Hello, Spring Boot! 我是" + demoUserBean.getNameCn() + ",我的簡介:" + demoUserBean.getDescription();
        System.out.println(result);
        return result;
    }
}

好了,現在我們重啟程式啟動類,看看配置檔案資訊是不是正常被注入到 Java Bean,並讀取到了。

訪問URL:http://localhost:8000/demo/user/hi

瀏覽器會列印:

Hello, Spring Boot! 我是測試,我的簡介:Dear All, name:SpringBoot-Tester, user_id:813655093, age:214

大功告成。其實,如果上面所說的 application-user.yml 檔案裡面的配置都是在 application.yml 檔案裡的話,那麼就不需要上面 2.1.2.讀取配置 DemoUserBean 裡面的 @PropertySource 註解,然後重複 2.1 的操作,同樣可以讀取到配置屬性。

 

2.3.多環境配置

現實的開發過程中,我們需要不同的配置環境。Spring Boot 為我們提供了此配置功能。格式為 application-{profile}.properties 或者 application-{profile}.yml,其中{profile}對應你的環境標識,比如: 

  • 開發環境:application-dev.yml
  • 測試環境:application-test.yml
  • 生產環境:application-prod.yml

開發環境 application-dev.yml 配置如下:

server:
  port: 8002
  servlet:
    context-path: /springboot-dev

測試環境 application-test.yml 配置如下:

server:
  port: 8004
  servlet:
    context-path: /springboot-test

我們只需要在 application.yml 中使用 spring.profiles.active 來設定對應的環境,就能切換不同的環境,也就是{profile}部分(上面定義的dev、test、prod):

server:
  port: 8000
spring:
  profiles:
    active: test
wei:
  name_cn: 測試
  age: ${random.int[1,300]}
  user_id: ${random.int}
  desc: Dear All, name:${wei.name_cn}, user_id:${wei.user_id}, age:${wei.age}

怎麼驗證呢?

我們再次重啟程式啟動類,沒錯,細心的你,應該也已經發現了,控制檯的日誌輸出告訴我們,其實程式啟動時已經把預設的埠切換到了你在 application.yml 中指定的環境 test 所對應的埠 8004,並且訪問所有的路由時需要加上 /springboot-test 根才能訪問到。

原來的URL:http://localhost:8000/demo/user/hi是不是已經無法訪問?

再來試試 http://localhost:8004/springboot-test/demo/user/hi,如你所見,瀏覽器正常列印了:

Hello, Spring Boot! 我是測試,我的簡介:Dear All, name:SpringBoot-Tester, user_id:556944052, age:205

 

3.總結

好了,至此,我們已經掌握了 Spring Boot 配置檔案的:

  1. 自定義屬性
  2. 自定義配置檔案
  3. 屬性(引數)間的引用
  4. 隨機值配置
  5. 多環境配置

最後,重點再講一下配置優先原則,Spring Boot 的配置檔案是按照自上而下的順序來解析的,也就是說,同樣的檔案,或者同樣的Key,順位最上的將會是最終有效的。

比如:如果你在resources目錄下同時有 application.properties 和 application.yml,那麼 application.properties 裡面的屬性就會覆蓋application.yml,因為相同優先順序位置,檔案 application.properties 在順位最上。

比如:src/main/resources/config 目錄下 application.properties 配置檔案將會覆蓋 src/main/resources 目錄下 application.properties 中相同的屬性。


原始碼:https://github.com/itanping/wei-springboot

Spring Boot   進擊:SpringBoot進擊 | 一淺出:Spring Boot簡單快速入門

Spring Cloud 進擊:SpringCloud進擊 | 一淺出:服務註冊與發現(Eureka)【Finchley版本】