1. 程式人生 > 其它 >SpringBoot - 配置檔案application.yml使用詳解(附:Profile多環境配置)

SpringBoot - 配置檔案application.yml使用詳解(附:Profile多環境配置)

1,基本介紹

(1)YAML是JSON的超集,簡潔而強大,是一種專門用來書寫配置檔案的語言,可以替代application.properties。 (2)在建立一個SpringBoot專案時,引入的spring-boot-starter-web依賴間接地引入了snakeyaml依賴,snakeyaml會實現對YAML配置的解析。 (3)YAML的使用非常簡單,利用縮排來表示層級關係,並且大小寫敏感。

2,YAML 配置與 Properties 配置的比較

  • 可以使用@PropertySource註解載入自定義的Properties配置檔案,但無法載入自定義的YAML檔案。
  • YAML支援列表的配置,而Properties不支援。

3,常規配置

(1)在Spring Boot專案中使用YAML只需要在resources目錄下建立一個application .yml檔案即可,這裡我們新增如下配置:
有了 application .yml 後我們可以將 resources 目錄下的 application.properties 檔案刪除(當然保留也沒問題),完全使用 YAML 完成檔案的配置。
注意:application.properties 的優先順序會比 application.yml 高,也就是說如果兩個檔案都存在,且兩個檔案都配置了同一個屬性,那麼會以 application.properties 裡的配置為準。
server:
  port: 8081
  servlet:
    context-path: /springboot-demo
  tomcat:
    uri-encoding: utf-8

其等效於application.properties中的如下配置:

server.port=8081
server.servlet.context-path=/springboot-demo
server.tomcat.uri-encoding=utf-8

(2)配置屬性之間也可以相互引用使用:

my:
  name: 小明
  age: 25
  info: name:${my.name} age:${my.age}

(3)配置檔案中可以使用${random}來生成各種不同型別的隨機值:

my:
  secret: ${random.value}
  number: ${random.int}
  bignumber: ${random.long}
  uuid: ${random.uuid}
  lessthanten: ${random.int(10)}
  numberinrange: ${random.int[1024,65536]}

4,將資料注入到屬性上

(1)假設我們有如下配置資料:

my:
  name: 小明
  age: 25

(2)在需要的地方我們使用@Value註解就可以將資料注入到屬性上:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
 
@RestController
public class HelloController {
    @Value("${my.name}")
    String name;
 
    @GetMapping("/hello")
    public String hello() {
        return "welcome to " + name;
    }
}

5,將資料注入到 Bean 中

有時候屬性太多了,一個個繫結到屬性欄位上太累,官方提倡繫結一個物件的bean。

(1)首先我們建立一個名為My的Bean,並將前面的配置資料注入到這個Bean中。

(1)@ConfigurationProperties中的prefix屬性描述了要載入的配置檔案的字首。
(2)Spring Boot採用了一種寬鬆的規則來進行屬性繫結:

  • 假設Bean中的屬性名為authorName,那麼配置檔案中的屬性可以是my.author_name、my.author-name、my.authorName或者my.AUTHORNAME
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
@Component
@ConfigurationProperties(prefix = "my")
public class My {
    private String name;
    private String age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAge() {
        return age;
    }
 
    public void setAge(String age) {
        this.age = age;
    }
}

6,將資料注入到一個集合中

(1)YAML還支援列表的配置:

my:
  name: 球
  favorites:
    - 足球
    - 籃球
    - 排球

(2)下面同樣將這組配置注入到Bean中,注意到其中favorites這個集合資料也自動注入到List屬性中:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
 
@Component
@ConfigurationProperties(prefix = "my")
public class My {
    private String name;
 
    private List<String> favorites;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public List<String> getFavorites() {
        return favorites;
    }
 
    public void setFavorites(List<String> favorites) {
        this.favorites = favorites;
    }
}

(3)然後我們在Controller中引入這個Bean使用即可:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
 
@RestController
public class HelloController {
    @Autowired
    My my;
 
    @GetMapping("/hello")
    public String hello() {
        return my.getName() + " : " + my.getFavorites();
    }
}

(4)執行結果

7,更復雜的配置:集合裡面放置物件

(1)YAML還支援更復雜的配置,即集合中也可以是一個物件:

my:
  users:
    - name: 小李
      age: 100
    - name: 小劉
      age: 200

(2)下面同樣將這組配置注入到Bean中:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
 
@Component
@ConfigurationProperties(prefix = "my")
public class Users {
    private List<User> users;
 
    public List<User> getUsers() {
        return users;
    }
 
    public void setUsers(List<User> users) {
        this.users = users;
    }
}
public class User {
    private String name;
    private String age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAge() {
        return age;
    }
 
    public void setAge(String age) {
        this.age = age;
    }
}

(3)然後我們在Controller中引入這個Bean使用即可:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
 
@RestController
public class HelloController {
    @Autowired
    Users users;
 
    @GetMapping("/hello")
    public String hello() {
        String result = "";
        for (User user : users.getUsers()) {
            result += user.getName() + ":" + user.getAge() + "<br>";
        }
        return result;
    }
}

(4)執行結果

8,使用命令列引數進行配置

(1)在命令列中通過java -jar命令啟動專案時,可以使用連續的兩個減號--對application.yml中的屬性值進行賦值。 (2)比如下面命令修改tomcat埠號為8081。其等價於在application.yml中新增屬性server.port=8081:
注意:如果 application.yml 中已經有同名屬性,那麼命令列屬性會覆蓋 application.yml 的屬性。
java -jar xx.jar --server.port=8081

9,配置檔案的優先順序

(1)同application.properties檔案一樣,Spring Boot專案中的application.yml配置檔案一共可以出現在如下4個位置(優先順序逐漸降低):
  • 專案根目錄下的config資料夾
  • 專案根目錄下
  • classpath下的config資料夾
  • classpath下

10,載入外部的配置檔案

(1)專案打包好以後,我們可以使用命令列引數的形式,啟動專案的時候來指定外部配置檔案的位置。

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/application.properties

(2)當然我們也可以指定外部配置所在的資料夾,啟動時會搜尋並使用該資料夾下的配置檔案:

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/

(3)我們還可以同時配置多個路徑,比如下面樣例先載入外部配置檔案,如果不存在外部配置檔案的話則使用包內預設的配置檔案:

java -jar xxx.jar --spring.config.location=/Volumes/BOOTCAMP/application.properties,classpath:/,classpath:/config/

附:使用 Profile 實現多環境配置

 我們在專案釋出之前,一般需要頻繁地在開發環境、測試環境以及生產環境之間進行切換,這個時候大量的配置需要頻繁更改(比如資料庫配置、redis 配置、mongodb 配置等等)。
    Spring Boot 的 Profile 就給我們提供瞭解決方案,它約定不同環境下的配置檔名稱規則為:
application-{profile}.yml,其中 {profile} 表示當前環境的名稱。

1,建立配置檔案

1)首先在resources目錄下建立兩個配置檔案:application-dev.yml和application-prod.yml此時,分別表示開發環境中的配置和生產環境中的配置。

(2)它們兩個分別設定不同的埠號。
#application-dev.yml
server:
  port: 8080
 
#application-prod.yml
server:
  port: 80

2,在 application.yml 中配置環境

(1)假設我們在application.yml中進行如下配置,則表示使用application-dev.yml配置檔案啟動專案。
spring:
  profiles:
    active: dev

(2)如果將dev改為prod,則表示使用application-prod.yml 啟動專案。

spring:
  profiles:
    active: prod

(3)專案啟動成功後,就可以通過相應的埠進行訪問了。

3,在程式碼中配置環境

(1)除了像前面那樣在application.yml中新增配置,我們也可以在程式碼中新增配置來完成。 (2)比如我們在啟動類的main方法上新增如下程式碼,表示使用application-dev.yml配置檔案啟動專案。
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
 
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplicationBuilder builder = new
                SpringApplicationBuilder(DemoApplication.class);
        builder.application().setAdditionalProfiles("dev");
        builder.run(args);
    }
}

4,在專案啟動時配置環境

我們也可以在專案打包成jar包後啟動時,在命令列中動態指定當前環境:

java -jar xxx.jar --spring.profiles.active=dev
早年同窗始相知,三載瞬逝情卻萌。年少不知愁滋味,猶讀紅豆生南國。別離方知相思苦,心田紅豆根以生。