目錄
2、@Value獲取值和@ConfigurationProperties獲取值比較
5、使用@ImportResource導入Spring的配置文件
(1)、在配置文件中指定spring.profiles.active屬性來激活
(2)、關於jar包外、jar包內的配置文件以及帶不帶profiles的順序區別
(3)、@Configuration註解類上的@PropertySource
1、Springboot啓動的時候加載主配置類時開啓自動配置功能
4、我們以HttpEncodingAutoConfiguration爲例來解釋自動配置原理
(2)、@EnableConfigurationProperties
(3)、@ConditionalOnWebApplication
一、配置文件
springboot使用一個全局的配置文件,配置文件名是固定的,一般有兩種寫法:
application.properties
application.yml
配置文件的作用:SpringBoot在底層都給我們自動配置了,而配置文件的作用就是修改SpringBoot自動配置的默認值。
之前的配置文件,都是使用的xml文件格式,但是YAML也可以做配置文件,YAML是以數據爲中心,比JSON、XML等等更適合做配置文件。
配置示例(將端口號設置爲8081)
server:
port: 8081
二、YAML語法
1、基本語法
k: v:
表示一對鍵值對(空格必須有)。以空格的縮進來控制層級關係,只要是左對齊的一列數據,都是同一個層級的。並且其屬性和值都是大小寫敏感的。
示例:
server:
port: 8081
path: /hello
2、值的寫法
(1)、字面量:普通的值(數字,字符串,布爾)
使用k: v:
對於字符串,默認不用加上單引號或者雙引號,""
雙引號不會轉義字符串裏面的特殊字符,特殊字符會作爲本身想表示的意思;''
單引號就會轉義字符,特殊字符最終只是一個普通的字符串數據。
(2)、對象、Map(屬性和值)
還是使用k:v:
方式,在下一行來寫對象的屬性和值的關係,注意縮進,例如:
friend:
lastName: zhangsan
age: 20
這樣表示lastName和age是friend對象的屬性。
也可以寫成行內寫法:friend: {lastName: zhangsan,age: 18}
(3)、數組(List、Set)
用-
表示數組中的一個元素
pets:
- cat,
- dog,
- pig
也可以寫成:pets: [cat,dog,pig]
三、配置文件值注入
在JavaBean類中加入@ConfigurationProperties
註解將配置文件中配置的每一個屬性的值映射到這個組件中,並且要將這個類加入到IOC容器中。要注意的是@ConfigurationProperties
默認是從全局配置文件中獲取值的。
1、一個簡單的示例
yml文件:
person:
lastName: zhangsan
age: 18
boss: false
birth: 2019/12/12
map: {k1: 1,k2: 2}
list:
- lisi
- zhaoliu
dog:
name: 小狗
age: 2
JavaBean(省略getter、setter、toString方法):
package com.cerr.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 將配置文件中配置的每一個屬性的值映射到這個組件中
* @ConfigurationProperties告訴Springboot將本類中的所有屬性和配置文件中相關的配置進行綁定
* prefix:配置文件中哪個下面的所有屬性進行配置
*
* 只有這個組件是容器中的組件,才能使用容器提供的ConfigurationProperties功能
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> map;
private List<Object> list;
private Dog dog;
}
我們可以導入配置文件處理器,以後編寫配置就有提示:
<!-- 導入配置文件處理器,配置文件進行綁定就會有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
剛剛在yml中的配置也可以在properties中配置:
person.last-name=張三
person.age=14
person.birth=2019/12/2
person.boss=false
person.map.k1=11
person.map.k2=22
person.list=a,b,c
person.dog.name=dog
person.dog.age=15
2、@Value獲取值和@ConfigurationProperties獲取值比較
對於yml或者properties配置文件,這兩個註解都可以獲取到配置文件的值,但是它們有以下的區別:
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的屬性 | 必須一個一個屬性的指定 |
鬆散語法(鬆散綁定) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
複雜類型封裝 | 支持 | 不支持 |
如果我們只是在某個業務邏輯中需要獲取一下配置文件的某個值時,我們使用@Value
比較方便;如果我們專門編寫了一個JavaBean來和配置文件進行映射,我們就直接使用@ConfigurationProperties
。
3、數據校驗
在類上標註@Validated
註解,並在你需要校驗的字段標註上對應的註解即可,假設我們在lastName
字段要使用@Eamil
校驗,則代碼如下:
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
@Email
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> map;
private List<Object> list;
private Dog dog;
}
4、使用@PropertySource
加載指定的配置文件
@PropertySource
這個註解可以加載指定的配置文件。
我們定義一個局部的配置文件,文件的位置位於類路徑下,如圖所示:
使用@PropertySource(value = {"classpath:person.properties"})
將該配置文件加載進來:
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> map;
private List<Object> list;
private Dog dog;
}
5、使用@ImportResource
導入Spring的配置文件
@ImportResource
的作用是導入Spring的配置文件,讓配置文件裏面的內容生效。
我們編寫了一個spring的配置文件,位於類路徑下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.cerr.springboot.service.HelloService" id="helloService"></bean>
</beans>
然後我們在Spring的單元測試中測試ioc容器中是否有helloService
這個bean:
@SpringBootTest
class Springboot01DemoApplicationTests {
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
boolean b = ioc.containsBean("helloService");
System.out.println(b);
}
}
結果卻是沒有這個bean,因爲此時這個配置文件並沒有被加載,因此我們需要使用@ImportResource
註解讓該文件加載進來,在主配置類中我們使用該註解:
//導入Spring的配置文件並讓其生效
@ImportResource(locations = {"classpath:bean.xml"})
@SpringBootApplication
public class Springboot01DemoApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01DemoApplication.class, args);
}
}
然後我們再一次在Spring的單元測試中測試,現在結果是有包含這個bean。
但是我們不推薦這種形式來給容器添加組件,Spring比較推薦使用以下這種方式:
6、使用配置類及@Bean
註解來給容器添加組件
Spring比較推薦使用配置類來給容器添加組件,首先我們先定義一個配置類:
package com.cerr.springboot.config;
import com.cerr.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 指明當前類是一個配置類,用來替代之前的Spring配置文件
*/
@Configuration
public class AppConfig {
//將方法的返回值添加到容器中,容器中這個組件默認的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("給容器中添加組件了");
return new HelloService();
}
}
該配置類使用了@Configuration
註解,表示其是一個配置類,然後在方法中使用了@Bean
註解,該註解的作用是將方法的返回值添加到ioc容器中,並且這個組件的id就是方法名。
我們還是使用剛剛的那個測試類來測試ioc容器中是否包含了這個bean:
四、配置文件佔位符
1、隨機數
例如在配置文件中給lastName
和age
字段加上隨機數:
person.last-name=張三${random.uuid}
person.age=${random.int}
2、佔位符獲取之前配置的值
person.last-name=張三${random.uuid}
person.dog.name=${person.last-name:hello}_dog
person.dog.name
的值就是person.last-name
的值拼上_dog,然後後面的:hello
的意思是,如果我們沒有在配置文件中指定person.last-name
的值,那麼那個佔位符的默認值就是hello。
五、Profile
1、多Profile文件
我們在編寫主配置文件的時候,文件名可以是application-{profile}.properties/yml,默認使用application.properties
文件的配置。
我們新建了application-dev.properties
,application-prod.properties
文件,分別指定其port
爲8083和80,然後在application.properties
文件中:
server.port=8080
spring.profiles.active=dev
第一句表示默認的環境配置(沒指定是哪種環境時)爲端口號是8080,第二句表示指定dev環境,即使用我們配置的application-dev.properties
文件。
2、yml支持多文檔塊形式
yml中使用---
可以將文件分爲多文檔,在不同的文檔中定義即可:
server:
port: 8081
path: /hello
spring:
profiles:
active: dev
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 80
spring:
profiles: prod
上述代碼中,在文檔2中我們定義了dev環境下的配置,文檔3中定義了prod環境下的配置,然後在文檔1中我們先定義了默認的配置,並且使用瞭如下格式來配置環境:
spring:
profiles:
active: dev
因此當前使用的環境是dev環境,所以此時的端口號應該是8083,我們啓動主啓動類:
3、激活指定Profile
(1)、在配置文件中指定spring.profiles.active
屬性來激活
- 對於properties文件,我們可以這樣激活:
spring.profiles.active=dev
(2)、使用命令行來激活
在終端中使用--spring.profiles.active=xxx
來激活,比如我們在配置yml配置文件中指定激活dev環境:
server:
port: 8081
path: /hello
spring:
profiles:
active: dev
但是我們在idea中加上命令行參數--spring.profiles.active=prod
表示我們想激活prod環境:
最後啓動之後發現使用的是prod的環境配置:
或者是將項目打包爲jar包後,在終端中運行該jar包且指定命令行參數也行:
命令行輸入:
java -jar springboot-01-demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
3、虛擬機參數
在IDEA中設置虛擬機參數:-Dspring.profiles.active=prod
然後啓動:
六、配置文件的加載位置
Springboot啓動會掃描以下位置的application.properties
或者application.yml
文件作爲Springboot的默認配置文件:
file:../config/
:根目錄下的config文件夾下file:../
:根目錄下classpath:/config/
:類路徑下的config文件夾下classpath:/
:類路徑下
以上是按照優先級從高到低的順序,所有位置的文件都會被加載,高優先級配置內容會覆蓋低優先級配置內容,稱爲互補配置。
例如我們在根目錄下新建一個config文件夾,並且新建一個application.properties
文件,配置port爲8082:
server.port=8082
在類路徑下的application.properties
文件中配置如下:
server.port=8081
#配置項目的訪問路徑
server.servlet.context-path=/boot1
因爲配置文件遵循高優先級配置內容覆蓋低優先級配置內容,所以這類路徑下文件的port配置會被第一個文件覆蓋,而第一個文件都沒配置server.servlet.context-path
,所以這個屬性的值還是第二個配置文件的值,我們訪問後:
我們可以通過配置spring.config.location
來改變默認配置
在項目打包好後,我們可以使用命令行參數的形式,啓動項目的時候來指定配置文件得新位置。
我們在E盤中新建一個application.properties
文件,然後設置port爲80:
server.port=80
我們將項目打包後,在IDEA的控制檯中運行該jar包:
默認端口爲80,因此localhost會省略80:
七、外部配置加載順序
Springboot可以從以下位置加載配置,優先級從高到低,高優先級的配置覆蓋低優先級的配置:
(1)、命令行參數
語法:--配置項=值
,多個參數使用空格分隔
打包後並在命令行輸入:
java -jar springboot-01-demo-0.0.1-SNAPSHOT.jar --server.port=8087
運行jar包並且修改server.port=8087
啓動後訪問8087端口能正常運行,訪問原來的8082端口不能用:
(2)、關於jar包外、jar包內的配置文件以及帶不帶profiles的順序區別
由jar包外向jar包內進行尋找,優先加載帶profiles,再來加載不帶profiles
此時我們項目內配置文件最高優先級的應該是端口爲8082,我們將項目打包,然後新建一個boot文件夾,將打包好的jar包放入文件夾中:
然後我們在該文件夾下新建一個application.properties
文件(在jar包外),裏面的配置如下:
server.port=8089
在命令行中輸入:
java -jar springboot-01-demo-0.0.1-SNAPSHOT.jar
此時的端口號爲8089,因此證明了我們定義在jar包外的這個配置文件是最高優先級的,我們訪問:
因爲訪問的路徑中有/boot2
,因此說明我們jar包內定義的配置文件也有起作用,只是有一部分被jar包外的覆蓋而已。
(3)、@Configuration
註解類上的@PropertySource
八、SpringBoot配置的原理
1、Springboot啓動的時候加載主配置類時開啓自動配置功能
主配置類中有@EnableAutoConfiguration
註解,我們下面來研究其作用:
2、@EnableAutoConfiguration
作用
利用AutoConfigurationImportSelector
給容器中導入一些組件。可以查看selectImports()
的內容:
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
} else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.filter(configurations, autoConfigurationMetadata);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
在selectImports
方法中調用了getAutoConfigurationEntry()
,其方法中的一句代碼List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
是獲取候選的配置,我們進入該方法:
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
該方法掃描所有jar包類路徑下META-INF/spring.factories
文件,並把掃描到的這些文件的內容包裝成properties對象。從properties中獲取到EnableAutoConfiguration.class
類名對應的值,然後把他們添加到容器中。
總結來說其作用就是將類路徑下META-INF/spring.factories
裏面配置的所有EnableAutoConfiguration
的值加入到容器中
每一個xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中,用他們來做自動配置。
3、每一個自動配置類進行自動配置
4、我們以HttpEncodingAutoConfiguration
爲例來解釋自動配置原理
首先這個類上有如下的註解:
@Configuration(
proxyBeanMethods = false
)
@EnableConfigurationProperties({HttpProperties.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
我們來逐一分析這些註解:
(1)、@Configuration
表示這是一個配置類。和以前編寫的配置文件一樣,也可以給容器添加組件
(2)、@EnableConfigurationProperties
這個註解表示啓動指定類的ConfigurationProperties功能,我們點進去HttpProperties
類,有如下註解:
@ConfigurationProperties(
prefix = "spring.http"
)
public class HttpProperties{
}
@ConfigurationProperties
註解的作用是從配置文件中獲取指定的值和bean的屬性來進行綁定。
因此所有在配置文件中能配置的屬性都是在xxxProperties類中封裝着,如果我們想要知道該配置文件能夠配置什麼功能,我們就可以參考某個功能對應的Properties類
對於這個例子,我們這個註解最後就是讓配置文件中對應的值和HttpProperties
綁定起來了,並加入到ioc容器中,爲後面我們要向容器中添加組件服務。
(3)、@ConditionalOnWebApplication
在Spring底層中有一個@Conditional
註解,判斷如果滿足指定的條件,整個配置類裏面的配置會生效。
因此這個@ConditionalOnWebApplication
就是判斷當前應用是否是web應用,如果是,則當前配置類生效。
(4)、@ConditionalOnClass
判斷當前項目有沒有這個類。@ConditionalOnClass({CharacterEncodingFilter.class})
表示判斷當前項目中有沒有CharacterEncodingFilter
這個類,這個類是SpringMVC中進行亂碼解決的過濾器。
(5)、@ConditionalOnProperty
判斷配置文件中是否存在某個配置,在這個例子中:
@ConditionalOnProperty(
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
表示判斷配置文件夾是否有spring.http.encoding.enabled這個配置,而matchIfMissing = true
表示如果不存在這個配置,這個配置也是默認生效的。
(6)、總結
因此AutoConfiguration配置類的作用就是不斷的判斷,最終決定這個配置類是否生效,如果生效的話,則給容器添加各種組件,這些組件的屬性是從對應的properties類中獲取的,這些類裏面的每一個屬性又是和配置文件綁定的
HttpEncodingAutoConfiguration
類中的一部分源碼如下:
public class HttpEncodingAutoConfiguration {
//通過@EnableConfigurationProperties註解,和SpringBoot的配置文件進行了映射
private final Encoding properties;
//只有一個有參構造器的情況下,參數的值就會從容器中拿
public HttpEncodingAutoConfiguration(HttpProperties properties) {
this.properties = properties.getEncoding();
}
@Bean
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
return filter;
}
}
5、結論
- SpringBoot啓動會加載大量的自動配置類。
- 我們看我們需要的功能有沒有SpringBoot默認寫好的自動配置類
- 我們再來看這個自動配置類中配置了哪些組件(如果我們要用的組件有,那我們就不需要再來配置)
- 給容器中自動配置類添加屬性的時候,會從
properties
類中獲取某些屬性,我們就可以在配置文件中指定這些屬性的值 - 本質上SpringBoot的各種
Properties
類就封裝了配置文件中的相關屬性,然後各種AutoConfiguration
自動配置類就會給容器添加各種組件。
九、@Conditional及其自動配置報告
@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存在指定項 |
自動配置類必須在一定的條件下才能生效;
我們可以通過設置debug=true
屬性,來讓控制檯打印自動配置報告,我們通過配置報告就知道哪些自動配置生效。