Spring boot 配置檔案詳解 (properties 和yml )
從其他框架來看 我們都有自己的配置檔案, hibernate有hbm,mybatis 有properties, 同樣, Spring boot 也有全域性配置檔案。
Springboot使用一個全域性的配置檔案,而且配置檔案的名字是固定的。 有兩種
- application.properties
- application.yml
springboot 配置檔案的作用是用來 修改SpringBoot自動配置的預設值;SpringBoot在底層都給我們自動配置好; 像我們Tomcat 啟動 預設配置埠是8080 . 如果要修改, 我們就在這兩個檔案的一種中來修改,
-
YML (也叫YAML : YAM Ain't Markup Language)
YAML Ain't Markup Language 這是一個遞迴寫法 ;
- YAML A Markup Language:是一個標記語言
- YAML isn't Markup Language:不是一個標記語言;
標記語言:
我們以前用的配置檔案,大多都使用 xxxx.xml 檔案 ;
YAML : 是一種以資料為中心的配置檔案, 比json,xml 等更適合做配置檔案
舉個栗子:
以 修改埠為例 : yml : server: port: 8081
xml : <server> <port>8081</port> </server>
xml 配置 將太多的浪費在了標籤上面。
yml 基本語法:
k:(空格)v:表示一對鍵值對(空格必須有);
以 空格 的縮排來控制層級關係;只要是左對齊的一列資料,都是同一個層級的
server: port: 8081 path:/hello
屬性和值也是大小寫敏感;
值的寫法:
-
字面量:普通的值(數字,字串,布林)
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
行內寫法
pets: [cat,dog,pig]
-
配置檔案注入
javaBean :
可以匯入配置檔案處理器依賴,以後編寫配置就會有程式碼提示;
程式碼展示配置檔案注入屬性值 :
1 package com.example.webservice.bean; 2 3 import org.springframework.boot.context.properties.ConfigurationProperties; 4 import org.springframework.stereotype.Component; 5 6 import java.util.Date; 7 import java.util.List; 8 import java.util.Map; 9 10 /** 11 * 12 * ConfigurationProperties(prefix ="person") 將本類中的所有屬性和配置檔案中的相關配置進行繫結 13 * prefix ="person 表示對哪個檔案進行繫結 14 * Component 表示這是一個容器, 只有在容器中 ConfigurationProperties 才能使用 15 */ 16 @Component 17 @ConfigurationProperties(prefix = "person") 18 public class Person { 19 20 private String name; 21 private Integer age; 22 private boolean man; 23 private Date birth; 24 private Map<String,Object>map; 25 private List<Object>list ; 26 private Son son ; 27 28 .....省略get/set 以及toString 方法 29 30 } 31 32 33 package com.example.webservice.bean; 34 35 public class Son { 36 37 private String name; 38 private Integer age ; 39 40 public String getName() { 41 return name; 42 } 43 44 public Integer getAge() { 45 return age; 46 } 47 48 public void setName(String name) { 49 this.name = name; 50 } 51 52 public void setAge(Integer age) { 53 this.age = age; 54 } 55 56 @Override 57 public String toString() { 58 return "Son{" + "name='" + name + '\'' + ", age=" + age + '}'; 59 } 60 } 61 62 63 properties檔案繫結的寫法 64 #註釋方法 Ctrl + / 65 person.name=爸爸 66 person.age=45 67 person.man=true 68 person.birth=2019/8/8 69 person.map.k1=h1 70 person.map.k2=h2 71 person.list=a,1,son 72 person.son.name=兒子 73 person.son,age=20 74 75 76 yml 檔案繫結的寫法: 77 78 person: 79 name: 爸爸 80 age: 25 81 birth: 2018/2/8 82 man: true 83 list: 84 - a 85 - 2 86 - son 87 map: {key1:value1,key2:value2} 88 son: 89 name: 兒子 90 age: 5
測試類 :
在我們的test 資料夾下 :
package com.example.webservice;
import com.example.webservice.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class WebserviceApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() { // 直接執行這個方法 ,而不是執行整個程式
System.out.println(person);
System.out.println("********************************************************");
}
控制檯列印結果 (使用的 yml 配置檔案)
properties配置檔案在idea中預設utf-8可能會亂碼 。 需要修改編碼;再輸入中文
都改成utf-8 ,再輸入中文就好了。
-
@Value獲取值和@ConfigurationProperties獲取值比較
| | @ConfigurationProperties | @Value |
| 功能 | 批量注入配置檔案中的屬性 | 一個個指定 |
| 鬆散繫結(鬆散語法) | 支援 | 不支援 |
| SpEL | 不支援 | 支援 |
| JSR303資料校驗 | 支援 | 不支援 |
| 複雜型別封裝 | 支援 | 不支援 |
配置檔案yml還是properties他們都能獲取到值;
如果說,我們只是在某個業務邏輯中需要獲取一下配置檔案中的某項值,使用@Value;
如果說,我們專門編寫了一個javaBean來和配置檔案進行對映,我們就直接使用@ConfigurationProperties;
-
配置檔案注入值資料校驗
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person { /** * <bean class="Person"> * <property name="name" value="字面量/${key}從環境變數、配置檔案中獲取值/#{SpEL}"></property> * <bean/> */ //name必須是郵箱格式 @Email //@Value("${person.name}") private String name; //@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; 。。。。。get/set /toString
-
@PropertySource&@ImportResource&@Bean
@PropertySource:載入指定的配置檔案;
/** * 將配置檔案中配置的每一個屬性的值,對映到這個元件中 * @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="name" value="字面量/${key}從環境變數、配置檔案中獲取值/#{SpEL}"></property> * <bean/> */ //name必須是郵箱格式 // @Email //@Value("${person.name}") private String name; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss; ```
-
@ImportResource:匯入Spring的配置檔案,讓配置檔案裡面的內容生效;
Spring Boot裡面沒有Spring的配置檔案,我們自己編寫的配置檔案,也不能自動識別; 想讓Spring的配置檔案生效,載入進來;@**ImportResource**標註在一個配置類上 @ImportResource(locations = {"classpath:beans.xml"}) 匯入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 id="helloService" class="com.example.webservice.controller.Hello"></bean> </beans> ``` SpringBoot推薦給容器中新增元件的方式;推薦使用全註解的方式 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、佔位符獲取之前配置的值,如果沒有可以是用:指定預設值
properties
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
3、Profile
1、多Profile檔案
我們在主配置檔案編寫的時候,檔名可以是 application-{profile}.properties/yml
預設使用application.properties的配置;
2、yml支援多文件塊方式
server:
port: 8081
spring:
profiles:
active: prod
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod #指定屬於哪個環境
```
4、啟用指定profile
1、在配置檔案中指定 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
5、配置檔案載入位置
springboot 啟動會掃描以下位置的application.properties或者application.yml檔案作為Spring boot的預設配置檔案
–file:./config/
–file:./
–classpath:/config/
–classpath:/
優先順序由高到底,高優先順序的配置會覆蓋低優先順序的配置;
SpringBoot會從這四個位置全部載入主配置檔案;**互補配置;
我們還可以通過spring.config.location來改變預設的配置檔案位置
專案打包好以後,我們可以使用命令列引數的形式,啟動專案的時候來指定配置檔案的新位置;指定配置檔案和預設載入的這些配置檔案共同起作用形成互補配置;
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
6、外部配置載入順序
SpringBoot也可以從以下位置載入配置; 優先順序從高到低;高優先順序的配置覆蓋低優先順序的配置,所有的配置會形成互補配置
1.命令列引數
所有的配置都可以在命令列上進行指定
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
多個配置用空格分開; --配置項=值
2.來自java:comp/env的JNDI屬性
3.Java系統屬性(System.getProperties())
4.作業系統環境變數
5.RandomValuePropertySource配置的random.*屬性值
由jar包外向jar包內進行尋找;
優先載入帶profile
7.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
8.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
再來載入不帶profile
9.jar包外部的application.properties或application.yml(不帶spring.profile)配置檔案
10.jar包內部的application.properties或application.yml(不帶spring.profile)配置檔案
[email protected]註解類上的@PropertySource
12.通過SpringApplication.setDefaultProperties指定的預設屬性
所有支援的配置載入來源;
[參考官方文件]
-
自動配置原理
配置檔案到底能寫什麼?怎麼寫?自動配置原理;
[配置檔案能配置的屬性參照]
1、**自動配置原理:
1)、SpringBoot啟動的時候載入主配置類,開啟了自動配置功能 [email protected]==
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的值加入到了容器中;
```properties # 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 ```View Code
每一個這樣的 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");
``
-
精髓:
**1)、SpringBoot啟動會載入大量的自動配置類**
**2)、我們看我們需要的功能有沒有SpringBoot預設寫好的自動配置類;**
**3)、我們再來看這個自動配置類中到底配置了哪些元件;(只要我們要用的元件有,我們就不需要再來配置了)**
**4)、給容器中自動配置類新增元件的時候,會從properties類中獲取某些屬性。我們就可以在配置檔案中指定這些屬性的值;**
xxxxAutoConfigurartion:自動配置類;
給容器中新增元件
xxxxProperties:封裝配置檔案中相關屬性;
2、細節
1、@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存在指定項 |
自動配置類必須在一定的條件下才能生效;
我們怎麼知道哪些自動配置類生效;
我們可以通過啟用 debug=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)