SpringBoot實戰:SpringBoot之本地配置(三)

springboot會自動加載application.yml和application.properties文件做爲默認配置文件,springboot會同時加載這兩個文件,可是會個優先級,順序高優先級的內容會覆蓋底優先級的內容,造成互補配置,若是在不一樣的目錄中存在多個配置文件,它的讀取順序是:
一、config/application.properties(項目根目錄中config目錄下)
二、config/application.yml
三、application.properties(項目根目錄下)
四、application.yml
五、resources/config/application.properties(項目resources目錄中config目錄下)
六、resources/config/application.yml
七、resources/application.properties(項目的resources目錄下)
八、resources/application.ymljava

下面咱們就來演示下,演示步驟以下:web

在resource/config文件下新增application.yml
spring:
  application:
    id: spring-boot-yml-demo  #應用id
    name : spring-boot-yml-demo #應用名稱

而application.properties文件添加一樣的配置spring

#應用id
spring.application.id=spring-boot-wusy-demo
#應用名稱
spring.application.name=spring-boot-wusy-demo
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

    @Value("${spring.application.name}")
    private String name;


    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world," + name;
    }
}

運行應用,打開瀏覽器,在地址欄輸入http://127.0.0.1:8787/api/demo/hello,觀察結果api

刪除application.yml中的配置後再重啓應用,在地址欄輸入http://127.0.0.1:8787/api/demo/hello,觀察結果瀏覽器

從演示結果能夠看出,確實是順序高優先級的內容會覆蓋底優先級的內容。springboot

同時優先級低的配置能夠讀取優先級高的配置,接下來演示在application.properties新增一個配置讀取application.yml中的spring.application.name的配置值。app

在applicataion.yml配置新增配置,並修改以前讀取配置的類,spring-boot

wusy.application.name = ${spring.application.name}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

    @Value("${wusy.application.name}")
    private String name;


    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world," + name;
    }
}

運行應用,打開瀏覽器,在地址欄輸入http://127.0.0.1:8787/api/demo/hello,觀察結果spa

經過以上的演示,知道配置文件如何經過優先級造成造成互補配置。code

相關文章
相關標籤/搜索