最全面的SpringBoot配置文件詳解

 像風同樣 Java筆記蝦html

Spring Boot在工做中是用到的愈來愈廣泛了,簡單方便,有了它,效率提升不知道多少倍。Spring Boot配置文件對Spring Boot來講就是入門和基礎,常常會用到,因此寫下作個總結以便往後查看。
java

一、配置文件

當咱們構建完Spring Boot項目後,會在resources目錄下給咱們一個默認的全局配置文件 application.properties,這是一個空文件,由於Spring Boot在底層已經把配置都給咱們自動配置好了,當在配置文件進行配置時,會修改SpringBoot自動配置的默認值。web

配置文件名是固定的spring

  • application.propertiesapache

但咱們能夠修改成數組

  • application.ymlspringboot

這兩個文件本質是同樣的,區別只是其中的語法略微不一樣。app

二、值的寫法

application.properties 配置文件比較簡單,形式以下dom

  • key = valueide

application.yml 配置文件使用YMAL語言,YMAL不是如XML般的標記語言,更適合做爲配置文件。

下面說下對於不一樣類型(字符串、數組)如何去規範書寫。

2.1 數字,字符串,布爾

一、直接寫

name=zhangsan

二、雙引號

不會轉義字符串裏面的特殊字符,特殊字符會做爲自己想表示的意思

name"zhangsan \n lisi"

輸出:
zhangsan
lisi

三、單引號

會轉義特殊字符,特殊字符最終只是一個普通的字符串數據

name: ‘zhangsan \n lisi’

輸出:

zhangsan \n lisi

2.2 對象、Map(屬性和值)(鍵值對)

例如配置類中的字段爲

Map<String,String> maps;

yml配置文件中,行內寫法

person.maps: {key1: value1,key2: value2}

須要注意:號後的空格,或者

person:
  maps:
   key: value

properties配置文件中

person.maps.key=value
2.3 數組(List、Set)

yml配置文件中

person:
  list:
   - 1
   - 2
   - 3

行內寫法

person:
  list: [1,2,3]

properties配置文件中

person.list[0]=1
person.list[1]=2
person.list[2]=3

三、自定義配置屬性

Spring Boot提供自定義配置組件,拿前面舉例的屬性來寫一個規範的配置文件

@Component // 或者@Configuration
@ConfigurationProperties(prefix = "person")
public class Person {
    private Map<String,String> maps;
    private List<String> list;
    private String name;

    public Map<StringString> getMaps() {
        return maps;
    }

    public void setMaps(Map<StringString> maps) {
        this.maps = maps;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@ConfigurationProperties 註解向Spring Boot聲明該類中的全部屬性和配置文件中相關的配置進行綁定。

  • prefix = "person":聲明配置前戳,將該前戳下的全部屬性進行映射。

@Component 或者@Configuration:將該組件加入Spring Boot容器,只有這個組件是容器中的組件,配置才生效。

四、配置自動提示

在配置自定義屬性時,若是想要得到和配置Spring Boot屬性自動提示同樣的功能,則須要加入下面的依賴:

<!--導入配置文件處理器,配置文件進行綁定就會有提示-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
</dependency>

如果依舊沒法自動提示,能夠嘗試開啓IDE的Annonation Processingimage.png


五、配置屬性校驗

自定義配置文件時,可使用@Validated註解對注入的值進行一些簡單的校驗,示例代碼

@Validated
@Configuration
@ConfigurationProperties(prefix = "person")
public class Person {
    @Email
    private String mail;

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
}

@Email 註解會對mail字段的注入值進行檢驗,若是注入的不是一個合法的郵件地址則會拋出異常。

其它常見註解:

  • @AssertFalse  校驗false

  • @AssertTrue  校驗true

  • @DecimalMax(value=,inclusive=)  小於等於value,inclusive=true,是小於等於

  • @DecimalMin(value=,inclusive=)  與上相似

  • @Max(value=)  小於等於value

  • @Min(value=)  大於等於value

  • @NotNull   檢查Null

  • @Past   檢查日期

  • @Pattern(regex=,flag=)  正則

  • @Size(min=, max=)  字符串,集合,map限制大小

  • @Validate   對po實體類進行校驗

上述的這些註解位於javax.validation.constraints包下,具體用法查看註釋便可瞭解。

六、自定義配置文件

除了在默認的application文件進行屬性配置,咱們也能夠自定義配置文件,例如新建 peoson.properties ,配置內容以下

person.mail=yster@foxmail.com

而後在配置類中使用@PropertySource註解注入該配置文件

@Configuration
@ConfigurationProperties(prefix = "person")
@PropertySource(value = "classpath:person.properties")
public class Person {
    private String mail;

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
}

測試@PropertySource註解不支持注入yml文件。

擴展:@ImportResource:該註解導入Spring的xml配置文件,讓配置文件裏面的內容生效。

例如:@ImportResource(locations = {"classpath:beans.xml"})

七、配置文件佔位符

Spring Boot配置文件支持佔位符,一些用法以下

7.1 隨機數
${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024,65536]}
7.2 默認值

佔位符獲取以前配置的值,若是沒有能夠是用:指定默認值

person.last-name=張三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15

八、多配置文件

8.1 多Profile文件

咱們在主配置文件編寫的時候,文件名能夠是 application-{profile}.properties/yml

默認使用application.properties的配置

8.2 yml支持多文檔塊方式

經過---能夠把一個yml文檔分割爲多個,並能夠經過 spring.profiles.active 屬性指定使用哪一個配置文件

server:
  port: 8081
spring:
  profiles:
    active: prod #指定使用哪一個環境

---
server:
  port: 8083
spring:
  profiles: dev  #指定屬於哪一個環境


---

server:
  port: 8084
spring:
  profiles: prod  #指定屬於哪一個環境
8.3 激活指定profile

不管是使用上述多文檔塊的方式,仍是新建application-dev.yml文件,均可以在配置文件中指定  spring.profiles.active=dev 激活指定的profile,或者

一、使用命令行:

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

能夠直接在測試的時候,配置傳入命令行參數

二、虛擬機參數:

-Dspring.profiles.active=dev

九、配置文件加載位置

springboot 啓動會掃描如下位置的application.properties或者application.yml文件做爲Spring boot的默認配置文件

  • –file:./config/

  • –file:./

  • –classpath:/config/

  • –classpath:/

優先級由高到底,高優先級的配置會覆蓋低優先級的配置;SpringBoot會從這四個位置所有加載主配置文件。

項目打包好之後,咱們可使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;指定配置文件和默認加載的這些配置文件共同起做用造成互補配置;

咱們還能夠經過spring.config.location來改變默認的配置文件位置,示例:

java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

十、外部配置加載順序

SpringBoot也能夠從如下位置加載配置,優先級從高到低,高優先級的配置覆蓋低優先級的配置,全部的配置會造成互補配置。

一、命令行參數

全部的配置均可以在命令行上進行指定

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087  --server.context-path=/abc

多個配置用空格分開,形如 --配置項=值

二、來自java:comp/env的JNDI屬性

三、Java系統屬性(System.getProperties())

四、操做系統環境變量

五、RandomValuePropertySource配置的random.*屬性值

由jar包外向jar包內進行尋找

優先加載帶{profile}

六、jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

七、jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

再來加載不帶profile

八、jar包外部的application.properties或application.yml(不帶spring.profile)配置文件

九、jar包內部的application.properties或application.yml(不帶spring.profile)配置文件

十、@Configuration註解類上的@PropertySource

十一、經過SpringApplication.setDefaultProperties指定的默認屬性

十一、自動配置原理

11.1 自動配置原理

一、SpringBoot啓動的時候加載主配置類,@EnableAutoConfiguration註解開啓了自動配置功能。

二、@EnableAutoConfiguration 做用:

  • 利用EnableAutoConfigurationImportSelector給容器中導入一些組件

  • 能夠查看selectImports()方法的內容;

  • List<String> configurations = getCandidateConfigurations(annotationMetadata,  attributes);獲取候選的配置

  • SpringFactoriesLoader.loadFactoryNames()
    掃描全部jar包類路徑下  META-INF/spring.factories
    把掃描到的這些文件的內容包裝成properties對象
    從properties中獲取到EnableAutoConfiguration.class類(類名)對應的值,而後把他們添加在容器中

將類路徑下  META-INF/spring.factories 裏面配置的全部EnableAutoConfiguration的值加入到了容器中

每個這樣的  xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中,用他們來作自動配置。

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
......

三、對每個自動配置類進行自動配置功能。

四、以HttpEncodingAutoConfiguration(Http編碼自動配置)爲例解釋自動配置原理;

@Configuration   //表示這是一個配置類,之前編寫的配置文件同樣,也能夠給容器中添加組件
@EnableConfigurationProperties(HttpEncodingProperties.class) //啓動指定類的ConfigurationProperties功能;將配置文件中對應的值和HttpEncodingProperties綁定起來;並把HttpEncodingProperties加入到ioc容器中

@ConditionalOnWebApplication 
//Spring底層@Conditional註解(Spring註解版),根據不一樣的條件,若是知足指定的條件,整個配置類裏面的配置就會生效;判斷當前應用是不是web應用,若是是,當前配置類生效

@ConditionalOnClass(CharacterEncodingFilter.class)  
//判斷當前項目有沒有這個類CharacterEncodingFilter;SpringMVC中進行亂碼解決的過濾器;

@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)  
//判斷配置文件中是否存在某個配置  spring.http.encoding.enabled;若是不存在,判斷也是成立的
//即便咱們配置文件中不配置pring.http.encoding.enabled=true,也是默認生效的;
public class HttpEncodingAutoConfiguration {

      //他已經和SpringBoot的配置文件映射了
      private final HttpEncodingProperties properties;

   //只有一個有參構造器的狀況下,參數的值就會從容器中拿
      public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
        this.properties = properties;
    }

    @Bean   //給容器中添加一個組件,這個組件的某些值須要從properties中獲取
    @ConditionalOnMissingBean(CharacterEncodingFilter.class) //判斷容器沒有這個組件
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
        return filter;
    }

根據當前不一樣的條件判斷,決定這個配置類是否生效。

一但這個配置類生效,這個配置類就會給容器中添加各類組件,這些組件的屬性是從對應的properties類中獲取的,這些類裏面的每個屬性又是和配置文件綁定的。

五、全部在配置文件中能配置的屬性都是在xxxxProperties類中封裝者,配置文件能配置什麼就能夠參照某個功能對應的這個屬性類

@ConfigurationProperties(prefix = "spring.http.encoding")  //從配置文件中獲取指定的值和bean的屬性進行綁定
public class HttpEncodingProperties {

   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

精髓:

1) SpringBoot啓動會加載大量的自動配置類

2) 先看咱們須要的功能有沒有SpringBoot默認寫好的自動配置類

3) 再來看這個自動配置類中到底配置了哪些組件(只要咱們要用的組件有,咱們就不須要再來配置了)

4) 給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。咱們就能夠在配置文件中指定這些屬性的值

xxxxAutoConfigurartion:自動配置類;給容器中添加組件;

xxxxProperties:封裝配置文件中相關屬性;

11.2 @Conditional註解

@Conditional派生註解(Spring註解版原生的@Conditional做用)

做用:必須是@Conditional指定的條件成立,纔給容器中添加組件,配置配裏面的全部內容才生效。

@Conditional擴展註解 做用(判斷是否知足當前指定條件)
@ConditionalOnJava 系統的java版本是否符合要求
@ConditionalOnBean 容器中存在指定Bean;
@ConditionalOnMissingBean 容器中不存在指定Bean;
@ConditionalOnExpression 知足SpEL表達式指定
@ConditionalOnClass 系統中有指定的類
@ConditionalOnMissingClass 系統中沒有指定的類
@ConditionalOnSingleCandidate 容器中只有一個指定的Bean,或者這個Bean是首選Bean
@ConditionalOnProperty 系統中指定的屬性是否有指定的值
@ConditionalOnResource 類路徑下是否存在指定資源文件
@ConditionalOnWebApplication 當前是web環境
@ConditionalOnNotWebApplication 當前不是web環境
@ConditionalOnJndi JNDI存在指定項

自動配置類必須在必定的條件下才能生效。

咱們怎麼知道哪些自動配置類生效?

咱們能夠經過在properties(yml)啓用  debug=true 屬性來讓控制檯打印自動配置報告,這樣咱們就能夠很方便的知道哪些自動配置類生效。

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:(自動配置類啓用的)
-----------------

   CodecsAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)

   CodecsAutoConfiguration.JacksonCodecConfiguration matched:
      - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
.......
Negative matches:(沒有啓動,沒有匹配成功的自動配置類)
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory''org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

   AopAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect''org.aspectj.lang.reflect.Advice''org.aspectj.weaver.AnnotatedElement' (OnClassCondition)

參考

docs.spring.io官方文檔:

https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#boot-features-external-config

相關文章
相關標籤/搜索