文章目錄
Spring Boot的配置文件
Spring Boot中的配置文件,默認爲application.properties 或 application.yml 或 application.yaml.
Spring Boot通過其自動配置的核心功能,動態加載開發者在配置文件中對相關功能的某些信息進行配置,從而方便了開發者對於相關功能的配置功能。
YAML 或 yml 格式配置文件,是Spring Boot 新加入的一種文件格式,關於它的介紹請查看我的博文YAML使用。
Spring Boot默認配置文件加載順序以及優先級
項目內部加載順序
Spring Boot默認情況下加載配置文件:
classpath: 根目錄
classpath: 根下config/
file:當前目錄
file:./config:當前目錄config/
classpath:/,classpath:/config/,file:./,file:./config/ 加載優先級自低到高,高優先級相同內容會覆蓋低優先級內容,不相同內容會形成互補效果。
ConfigFileApplicationListener.java
public class ConfigFileApplicationListener
implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
private static final String DEFAULT_PROPERTIES = "defaultProperties";
// 默認配置文件加載目錄,且優先級自低到高。
// Note the order is from least to most specific (last one wins)
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
// 默認配置文件名稱
private static final String DEFAULT_NAMES = "application";
private static final Set<String> NO_SEARCH_NAMES = Collections.singleton(null);
private static final Bindable<String[]> STRING_ARRAY = Bindable.of(String[].class)
項目外部配置文件加載順序:
當我們項目已經打成jar包後,可能會碰到重新配置某些環境信息,又不想重新打jar包,Spring Boot支持在jar包外的配置文件使用,如下:
1.命令行參數
2.來自java:comp/env的JNDI屬性
3.Java系統屬性(System.getProperties())
4.操作系統環境變量
5.RandomValuePropertySource配置的random.*屬性值
6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
7.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
8.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
9.jar包內部的application.properties或application.yml(不帶spring.profile)配置文件
10.@Configuration註解類上的@ImportSource
11.通過SpringApplication.setDefaultProperties指定的默認屬性
由jar包外向jar包內的順序進行掃描加載;
優先加載名稱帶有profile的,再加載不帶profile。
自定義指定配置文件路徑
通過以上我們可以發現,Spring Boot支持自定義配置掃描配置文件的路徑,如下:
application-prod.yml
server:
port: 8094
項目外,啓動Spring Boot項目命令:
java -jar springboot-manual-1.0-SNAPSHOT.jar --spring.config.location=C:\Users\Desktop\test\application-prod.yml
或
java -jar -Dspring
注意:spring.config.location 或者spring.config.location在配置文件中均不生效,只有在命令行或虛擬機參數等纔會生效。
Spring Boot 指定啓動profile的方式
Spring Boot 多個Profile環境配置,方便了開發人員靈活的配置運行環境,有以下幾種方式:
命令行參數指定profile
將Spring Boot 打成jar包,命令行啓動,uat 接口爲8093。
java -jar springboot-manual-1.0-SNAPSHOT.jar --spring.profiles.active=uat
JVM虛擬機參數指定profile
在IDEA中點擊Run–>Edit Configuration
VM options:-Dspring.profiles.active=uat
配置文件指定profile:
在application配置文件中增加以下:
spring:
profiles:
active: dev
操作系統環境變量 :
創建系統環境變量,例如:
spring.profiles.active -> SPRING_PROFILES_ACTIVE