基于SpringBoot bootstrap.yml配置未生效的解決
我就廢話不多說了,大家還是直接看代碼吧~
<!--需要引入該jar才能使bootstrap配置文件生效--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-context</artifactId> </dependency>
補充知識:SpringBoot不讀取bootstrap.yml/properties文件
今天寫創建了一個SpringBoot項目,配置文件從其他項目拷貝了一份bootstrap.yml
之前一直用的application.yml
心想:application.yml 優先級沒有bootstrap.yml 高,bootstrap配置文件肯定沒問題
項目一跑來,發現配置文件里面的內容沒讀取到。
之后通過各種查資料,才明白了application.yml 和bootstrap.yml 的區別,不僅僅是優先級的問題。
先說我的問題是什么原因吧:
SpringBoot 項目中如果沒有依賴 spring-cloud-context 的話,是不會讀取bootstrap.properties 文件
也就是說
bootstrap.yml配置是SpringCloud項目才會用到的。
如果你的項目僅僅是一個SpringBoot項目,只會識別application.yml配置文件。
由于SpringCloud是基于SpringBoot構建的,所有SpringCloud項目兩種文件都會識別,這個時候才有優先級的說法,SpringCloud項目是會優先讀取bootstrap配置在讀取application配置。
引用Spring官網的一句話
A Spring Cloud application operates by creating a “bootstrap” context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.
SpringCloud 應用是基于 一個 “bootstrap”的上下文運行的。
也就說明了 bootstrap這個配置是SpringCloud 應用才會用的。
而且這個配置是不能被覆蓋的,也就是優先級比application配置中的高。
什么配置在application配置?什么配置在bootstrap里面配置?
1、當使用 Spring Cloud Config Server 的時候,spring.application.name 和 spring.cloud.config.server.git.uri應該在 bootstrap.yml 里面指定
2、一些加密解密的配置也應該配置在bootstrap里面
英文好的可以參考官網文章:
https://cloud.spring.io/spring-cloud-commons/multi/multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-properties
以上這篇基于SpringBoot bootstrap.yml配置未生效的解決就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: