1. 程式人生 > >《深入理解Spring Cloud與微服務構建》學習筆記(二)~使用Spring Boot配置檔案

《深入理解Spring Cloud與微服務構建》學習筆記(二)~使用Spring Boot配置檔案

接上一章demo: 一、IDEA在建立完Spring Boot專案時,會在src/main/resources目錄下生成一個application.properties檔案,使用者進行系統屬性配置,預設為空。Spring Boot也支援yml格式的檔案配置,當前使用yml檔案配置進行操作。

resources下新建一個檔案:application.yml ,手寫測試資料:

database:
    type: mysql
    username: root
    password: root

要讀取配置檔案的屬性值,只需在變數上加@Value("${屬性名}")註解,就可以將配置檔案 application.yml 的屬性值賦給變數。

我們可以在預設Controller進行,也可以新建一個controller進行操作,此處新建一個Controller類ApplicationController.java,並將每一個變數進行繫結,如下:


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApplicationController {

    @Value("${database.type}")
    private String type ;
    @Value("${database.username}")
    private String username ;
    @Value("${database.password}")
    private  String password ;

    @GetMapping("/my")
    public String my(){
        StringBuffer sb = new StringBuffer();
        sb.append("****************");
        sb.append("<br/>");
        sb.append("type="+this.type);
        sb.append("<br/>");
        sb.append("username="+this.username);
        sb.append("<br/>");
        sb.append("password="+this.password);
        sb.append("<br/>");
        sb.append("*****end********");
        return sb.toString() ;
    }
}

重新啟動專案,瀏覽器訪問http://localhost:8080/my ,效果如下: 這說明配置檔案application.yml裡的屬性: database.type、database.username、database.password 已經成功讀入應用程式,大功告成!

二、假如配置屬性很多,那麼程式碼裡是不是要寫很多變數來一個一個繫結,這樣就顯得很麻煩,在這裡我們可以將配置檔案裡的屬性賦值給實體類。

需要先建立一個ConfigBean.java 類,此類必須加一個註解@ConfigurationProperties ,表明該類為配置屬性類,並加上配置的prefix。還需要新增@Component註解, Spring Boot 啟動時通過包掃描將該類作為一個Bean 注入 IoC 容器中。

      建立一個Controller ,讀取 ConfigBean 類的屬性。在 Controller 類上,加 @EnableConfigurationProperties 註解,並指明 ConfigBean 類。

執行成功!大功告成!