springboot系列三、spirngboot中配置檔案詳解
一、配置檔案
SpringBoot使用一個全域性的配置檔案,配置檔名是固定的,配置檔案主要分為以下兩種
•application.properties
•application.yml
配置檔案的作用:修改SpringBoot自動配置的預設值;SpringBoot在底層都給我們自動配置好;
YAML(YAML Ain't Markup Language)
YAML A Markup Language:是一個標記語言
YAML isn't Markup Language:不是一個標記語言;
標記語言:
以前的配置檔案;大多都使用的是 xxxx.xml檔案;
YAML:以資料為中心
YAML:配置例子
server:
port: 8081
XML:
<server>
<port>8081</port>
</server>
二、YAML語法
1、基本語法
k:(空格)v:表示一對鍵值對(空格必須有);
以空格的縮排來控制層級關係;只要是左對齊的一列資料,都是同一個層級的
server:
port: 8081
path: /hello
屬性和值也是大小寫敏感;
2、值的寫法
字面量:普通的值(數字,字串,布林)
k: v:字面直接來寫;
字串預設不用加上單引號或者雙引號;
"":雙引號;不會轉義字串裡面的特殊字元;特殊字元會作為本身想表示的意思
name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
'':單引號;會轉義特殊字元,特殊字元最終只是一個普通的字串資料
name: ‘zhangsan \n lisi’:輸出;zhangsan \n lisi
物件、Map(屬性和值)(鍵值對):
k: v:在下一行來寫物件的屬性和值的關係;注意縮排
物件還是k: v的方式
friends:
lastName: zhangsan
age: 20
行內寫法:
friends: {lastName: zhangsan,age: 18}
陣列(List、Set):
用- 值表示陣列中的一個元素
pets:
- cat
- dog
- pig
people:
- name
- age
- address
行內寫法
pets: [cat,dog,pig]
三、配置檔案值注入
配置檔案
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
javaBean:
/**
* 將配置檔案中配置的每一個屬性的值,對映到這個元件中
* @ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置檔案中相關的配置進行繫結;
* prefix = "person":配置檔案中哪個下面的所有屬性進行一一對映
*
* 只有這個元件是容器中的元件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
我們可以匯入配置檔案處理器,以後編寫配置就有提示了
<!--匯入配置檔案處理器,配置檔案進行繫結就會有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
①在springboot單元測試中,bean物件注入失敗的問題
我的單元測試裡面顯示bean物件注入失敗,我們都知道spring中使用註解會在spring配置檔案中開啟掃描註解的方法,springmvc也是一樣,那麼spring-boot也會提供一個掃描註解的方法叫做@ComponentScan(basePackages = {"com.bdqn.Controller"}),表示會掃描到basePackages中所有約定包下面的所有註解
後來經研究發現,SpringBoot專案的Bean裝配預設規則是根據Application類所在的包位置從上往下掃描! “Application類”是指SpringBoot專案入口類。這個類的位置很關鍵:
如果Application類所在的包為:io.github.gefangshuai.app
,則只會掃描io.github.gefangshuai.app
包及其所有子包,如果service或dao所在包不在io.github.gefangshuai.app
及其子包下,則不會被掃描!
本次測試的是yml配置檔案對映動態繫結到實體類中,但是在單元測試類中出現bean物件掃描失敗
這裡給大家說明兩點要注意的地方
①測試檔案的專案名稱要和啟動類的專案名稱保持一致
②掃描註解只有放在啟動類上面才會起到掃描bean物件的作用
實現步驟如下
/***
* 將配置檔案中配置的每一個值對映到這個元件中
* * @ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置檔案中相關的配置進行繫結;
* * prefix = "person":配置檔案中哪個下面的所有屬性進行一一對映
* *
* * 只有這個元件是容器中的元件,才能容器提供的@ConfigurationProperties功能;
* *
* */
@Component //把實體類注入容器
@ConfigurationProperties(prefix = "person")
public class Person {
// alt+insert
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
###aplication.yml配置檔案
person:
lastName: hello
age: 18
boss: false
birth: 2017/12/12
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
springboot啟動類
@SpringBootApplication
@ComponentScan(basePackages = {"com.bdqn"})
/**
* 當測試啟動類和Controller不位於同一個包下面時候需要
* 配置@ComponentScan(basePackages = {"com.bdqn.Controller"})去掃描controller的路徑
*/
public class SpringBootQuickApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootQuickApplication.class, args);
}
}
在springboot提供的單元測試類裡面進行測試
啟動單元測試類,拿到了application.yml檔案中配置的值
②@Value獲取值和@ConfigurationProperties獲取值比較
配置檔案yml還是properties他們都能獲取到值;
如果說,我們只是在某個業務邏輯中需要獲取一下配置檔案中的某項值,使用@Value;
測試程式碼如下
application.properties檔案,實體類的程式碼還是不變
##修改spring-boot給我們底層的預設配置
#預設是的的是utf-8
#配置person的值
person.last-name=tom
person.age=18
person.boss=true
person.birth=2017/10/1
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
@RestController
/**
* 相當於 Contoller和RequestBody的合體,都是把資料響應給瀏覽器
*/
@RequestMapping("/test")
public class HelloController {
@Value("${person.last-name}")
private String name;
@RequestMapping("/hello")
public String hello(){
return "hello you name is"+name;
}
}
③、配置檔案注入值資料校驗
@Component
@ConfigurationProperties(prefix = "person")
@Validated //專門驗證資料的格式是否正確
public class Person {
/**
* <bean class="Person">
* <property name="lastName" value="字面量/${key}從環境變數、配置檔案中獲取值/#{SpEL}"></property>
* <bean/>
*/
//lastName必須是郵箱格式
@Email
//@Value("${person.last-name}")
private String lastName;
//@Value("#{11*2}")
private Integer age;
//@Value("true")
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
④@PropertySource&@ImportResource&@Bean
/**
* 將配置檔案中配置的每一個屬性的值,對映到這個元件中
* @ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置檔案中相關的配置進行繫結;
* prefix = "person":配置檔案中哪個下面的所有屬性進行一一對映
*
* 只有這個元件是容器中的元件,才能容器提供的@ConfigurationProperties功能;
* @ConfigurationProperties(prefix = "person")預設從全域性配置檔案中獲取值;
*
*/
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
/**
* <bean class="Person">
* <property name="lastName" value="字面量/${key}從環境變數、配置檔案中獲取值/#{SpEL}"></property>
* <bean/>
*/
//lastName必須是郵箱格式
// @Email
//@Value("${person.last-name}")
private String lastName;
//@Value("#{11*2}")
private Integer age;
//@Value("true")
private Boolean boss;
@ImportResource:匯入Spring的配置檔案,讓配置檔案裡面的內容生效;
Spring Boot裡面沒有Spring的配置檔案,我們自己編寫的配置檔案,也不能自動識別;
想讓Spring的配置檔案生效,載入進來;@ImportResource標註在一個啟動Application配置類上,ApplicationContext.xml
<bean id="helloService" class="com.bdqn.Controller.service.HelloService"></bean>
單元測試類程式碼如下,不加入@ImportResource情況下
@Test
public void TestService(){
//測試容器中是否有這個值
Boolean bean= (Boolean) ioc.containsBean("helloService");
System.out.println(bean);
}
@SpringBootApplication
@ComponentScan(basePackages = {"com.bdqn"})
//引入spring的配置檔案
@ImportResource(locations = {"classpath:ApplicationContext.xml"})
/**
* 當測試啟動類和Controller不位於同一個包下面時候需要
* 配置@ComponentScan(basePackages = {"com.bdqn.Controller"})去掃描controller的路徑
*/
public class SpringBootQuickApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootQuickApplication.class, args);
}
}
不用編寫Spring的配置檔案
SpringBoot推薦給容器中新增元件的方式;推薦使用全註解的方式,但是我覺得太麻煩了,每次建立一個bean都要建立一個類物件
1、配置類@Configuration------>Spring配置檔案
2、使用@Bean給容器中新增元件
/**
* @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置檔案
*
* 在配置檔案中用<bean><bean/>標籤新增元件
*
*/
@Configuration
public class MyAppConfig {
//將方法的返回值新增到容器中;容器中這個元件預設的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置類@Bean給容器中新增元件了...");
return new HelloService();
}
}
⑤、配置檔案佔位符
1、隨機數
${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
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.maps這個值,後面person.dog.name想用一下前面的值
person.dog.name=${person.maps:hello}_dog
person.dog.age=15
四、Profile
是springboot用來做多環境支援的,開發環境、測試環境、執行環境
①、多Profile檔案
我們在主配置檔案編寫的時候,檔名可以是 application-{profile}.properties/yml
預設使用application.properties的配置;
②、yml支援多文件塊方式
server:
port: 8081
spring:
profiles:
active: prod
---//三個橫線+回車
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod #指定屬於哪個環境
③、啟用指定profile
1、在application.properties配置檔案中指定 spring.profiles.active=dev
2、命令列:
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
可以直接在測試的時候,配置傳入命令列引數
3、虛擬機器引數;
-Dspring.profiles.active=dev
五、配置檔案載入位置或順序
springboot 啟動會掃描以下位置的application.properties或者application.yml檔案作為Spring boot的預設配置檔案
–file:./config/
–file:./
–classpath:/config/
–classpath:/
入圖上所展示,優先順序由高到底,高優先順序的配置會覆蓋低優先順序的配置;
SpringBoot會從這四個位置全部載入主配置檔案;互補配置;
==我們還可以通過spring.config.location來改變預設的配置檔案位置==
專案打包好以後,我們可以使用命令列引數的形式,啟動專案的時候來指定配置檔案的新位置;指定配置檔案和預設載入的這些配置檔案共同起作用形成互補配置;
先輸入 cd target
在輸出dir
輸入:java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=F:/application.properties(裡面是湍口號內容)也可以執行專案
六、外部配置載入順序
==SpringBoot也可以從以下位置載入配置; 優先順序從高到低;高優先順序的配置覆蓋低優先順序的配置,所有的配置會形成互補配置==
1.命令列引數
所有的配置都可以在命令列上進行指定
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.port=8087
--server.context-path=/abc //訪問專案名稱,但是需要修改多個配置的時候這麼寫的話?顯得很累贅
可以專門寫一個外部配置檔案
多個配置用空格分開; --配置項=值
2.來自java:comp/env的JNDI屬性
3.Java系統屬性(System.getProperties())
4.作業系統環境變數
5.RandomValuePropertySource配置的random.*屬性值
==由jar包外向jar包內進行尋找;==
==優先載入帶profile==
優先載入,外部jar包旁邊的配置檔案
6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案**
7.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
==再來載入不帶profile==
8.jar包外部的application.properties或application.yml(不帶spring.profile)配置檔案
9.jar包內部的application.properties或application.yml(不帶spring.profile)配置檔案
10.@Configuration註解類上的@PropertySource
11.通過SpringApplication.setDefaultProperties指定的預設屬性
所有支援的配置載入來源;
七、自動配置原理
配置檔案到底能寫什麼?怎麼寫?自動配置原理;
1、自動配置原理:
1)、SpringBoot啟動的時候載入主配置類,開啟了自動配置功能 ==@EnableAutoConfiguration==
2)、@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的值加入到了容器中;==
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
每一個這樣的 xxxAutoConfiguration類都是容器中的一個元件,都加入到容器中;用他們來做自動配置;
3)、每一個自動配置類進行自動配置功能;
4)、以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類中獲取的,這些類裡面的每一個屬性又是和配置檔案繫結的;
5)、所有在配置檔案中能配置的屬性都是在xxxxProperties類中封裝;配置檔案能配置什麼就可以參照某個功能對應的這個屬性類
@ConfigurationProperties(prefix = "spring.http.encoding") //從配置檔案中獲取指定的值和bean的屬性進行繫結
public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
精髓:springboot裡面的HttpEncodingProperties會自動配置好很多注元件
1)、SpringBoot啟動會載入大量的自動配置類
2)、我們看我們需要的功能有沒有SpringBoot預設寫好的自動配置類;
3)、我們再來看這個自動配置類中到底配置了哪些元件;(只要我們要用的元件有,我們就不需要再來配置了)
4)、給容器中自動配置類新增元件的時候,會從properties類中獲取某些屬性。我們就可以在配置檔案中指定這些屬性的值;
xxxxAutoConfigurartion:自動配置類;
給容器中新增元件
xxxxProperties:封裝配置檔案中相關屬性;
2、細節
1、@Conditional派生註解(Spring註解版原生的@Conditional作用)
作用:必須是@Conditional指定的條件成立,才給容器中新增元件,配置配裡面的所有內容才生效;
自動配置類必須在一定的條件下才能生效;
我們怎麼知道哪些自動配置類生效;
==我們可以通過啟用 在全域性配置檔案aplication.properties中開啟 debug=true屬性;來讓控制檯列印自動配置報告==,這樣我們就可以很方便的知道哪些自動配置類生效;
#開啟Springboot中的debug
debug=true
#配置埠號
server.port=8089
#我們能配置那些都是來源於properties類
spring.http.encoding.enabled=true
spring.http.encoding.charset=utf-8
spring.http.encoding.force=true
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches:(自動配置類啟用的)
-----------------
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
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' (OnClassCondition)