SpringBoot 配置檔案
一、配置檔案
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:以資料為中心,比json、xml等更適合做配置檔案;
YAML:配置例子
server:
port: 8081
xml:
<server>
<port>8081</port>
</server>
二、YAML語法
1、基本語法
k:(空格)v:表示一對鍵值對(空格必須有);
以空格的縮排來控制層級關係;只要是左對齊的一列資料,都是同一個層級的
server:
port: 8081
path: /hello
屬性和值也是大小寫敏感;
2、值的寫法
2.1 字面量:普通的值(數字,字串,布林)
k: v:字面直接來寫;
字串預設不用加上單引號或者雙引號;
"":雙引號;不會轉義字串裡面的特殊字元;特殊字元會作為本身想表示的意思
name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
'':單引號;會轉義特殊字元,特殊字元最終只是一個普通的字串資料
name: ‘zhangsan \n lisi’:輸出;zhangsan \n lisi
2.2 物件、Map(屬性和值)(鍵值對):
k: v:在下一行來寫物件的屬性和值的關係;注意縮排
物件還是k: v的方式
friends:
lastName: sang
age: 18
行內寫法
friends: {lastName: sang,age: 18}
2.3 陣列(List Set)
用- 值表示陣列中的一個元素
pets:
- cat
- dog
- pig
行內寫法
pets: [cat,dog,pig]
三、@ConfigurationProperties配置檔案值注入
1.pom.xml中新增依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.3.0.RELEASE</version>
<optional>true</optional>
</dependency>
書寫配置檔案的時候會提示
2.配置檔案
person:
lastName: sang
age: 18
boss: false
maps: {k1: v1,k2: v2}
lists:
- li
- san
dog:
name: wang
age: 12
如果使用properties檔案中文亂碼的話需要修改檔案的編碼
3.JavaBean:
package com.slp.springboot02config.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* @ClassName Person
* @Description 將配置檔案中配置的每一個屬性的值,對映到這個元件中
* ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置檔案中的相關的配置進行繫結;
* prefis = "person":配置檔案中哪個下面的所有屬性一一對映
*
* 只有這個組價是容器中的元件,才能使用容器提供的@ConfigurationProperties功能
* @Author sanglp
* @Date 2020/5/22 17:42
* @Version 1.0
**/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private int age;
private Boolean boss;
private List<Object> lists;
private Map<String,Object> maps;
private Dog dog;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", lists=" + lists +
", maps=" + maps +
", dog=" + dog +
'}';
}
}
package com.slp.springboot02config.bean;
/**
* @ClassName Dog
* @Description TODO
* @Author zixin
* @Date 2020/5/22 17:44
* @Version 1.0
**/
public class Dog {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.slp.springboot02config;
import com.slp.springboot02config.bean.Person;
import org.junit.jupiter.api.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 指定使用Spring處理器而不是junit
*/
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
4.結果:
Person{lastName='sang', age=18, boss=false, lists=[li, san], maps={k1=v1, k2=v2}, dog=com.slp.springboot02config.bean.Dog@6fa69af7}
四、@Value獲取值
其它配置和上方一致,只看一下javabean的改變
package com.slp.springboot02config.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
public class PersonNew {
/**
* <bean class="Person2">
* <propertu name="lastName" value="sang"></propertu>
* </bean>
* person.last-name :對應的是配置檔案中的名稱
*/
@Value("person.last-name")
private String lastName;
@Value("#{11*2}")
private int age;
@Value("true")
private Boolean boss;
private List<Object> lists;
private Map<String,Object> maps;
private Dog dog;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
五、@Value和@ConfigurationProperties注入的區別
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置檔案中的屬性 | 一個個指定 |
鬆散繫結 | 支援 | 不支援 |
SPEL | 不支援 | 支援 |
JSR303資料校驗 | 支援 | 不支援 |
//JSR303校驗
@Component
@ConfigurationProperties(prefix = "personval")
@Validated
public class PersonValidate {
@Email
private String lastName;
}
需要新增jar包
<!--jsr3引數校驗器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
六、@PropertySource&@ImportResource
1.@PropertySource
載入指定配置檔案
package com.slp.springboot02config.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "personsource")
public class PersonPropertySource {
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "PersonPropertySource{" +
"lastName='" + lastName + '\'' +
'}';
}
}
person.properties
personsource.lastName=sang
測試結果
PersonPropertySource{lastName='sang'}
2.@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 id="helloService" class="com.slp.springboot02config.service.HelloService"></bean>
</beans>
測試Spring容器是否包含這個bean
package com.slp.springboot02config;
import com.slp.springboot02config.bean.Person;
import com.slp.springboot02config.bean.PersonPropertySource;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 可以在測試期間自動注入
* RunWith 指定使用Spring處理器而不是junit
*/
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Autowired
PersonPropertySource personPropertySource;
@Autowired
ApplicationContext ioc ;
@Test
void contextLoads() {
System.out.println(ioc.containsBean("helloService"));
}
}
輸出結果為false,說明此時裡面還沒有這個bean,說明自己編寫的配置檔案不能自動識別,想讓Spring的配置檔案生效,載入進來,需要將@ImportResource標註在主配置類上,修改啟動類內容為如下
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}
}
再進行測試則會輸出true,說明載入成功。
但是這樣會很麻煩,加一個就要修改一下,SpringBoot推薦給容器中新增元件的方式:使用全註解的方式(@Bean)
去掉主配置類上的@ImportResource
//@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot02ConfigApplication.class, args);
}
}
新增一個配置類
package com.slp.springboot02config.config;
import com.slp.springboot02config.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration:指明當前類是一個配置類 就是來替代之前的Spring配置檔案
* 在配置檔案中用<bean></bean>來新增元件
*/
@Configuration
public class MyAppConfig {
/**
* @Bean:將方法的返回值新增到容器中,容器中的元件預設的id就是方法名
* @return
*/
@Bean
public HelloService helloService(){
return new HelloService();
}
}
七、配置檔案佔位符
1.隨機數
${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024,65536]}
2.佔位符獲取之前配置的值,如果沒有可以使用:之後的預設值
person.last-name=sang${random.int}
person.dog.name=${person.hello:hello}_dog
八.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
3. 啟用制定profile
- 在配置檔案application.properties中指定
spring.profiles.active=dev
-
命令列
java -jar 專案.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-02.jar --spring.config.location=D:/application.properties
十、外部配置載入順序
SpringBoot可以從以下位置載入,優先順序由高到低,形成互補。
-
命令列引數
java -jar spring-boot.jar --server.port=8081 --server.context-path=/hello
-
來自java:comp:/env的JNDI屬性
-
java系統屬性(System.getProperties())
-
作業系統環境變數
-
RandomValuePropertySource配置的random.*屬性值
-
jar包外部的application-{profile}.properties或application.yml(帶spring.profile)
-
jar包內部的application-{profile}.properties或application.yml(帶spring.profile)
-
jar包外部的application-{profile}.properties或application.yml(不帶spring.profile)
-
jar包內部的application-{profile}.properties或application.yml(不帶spring.profile)
-
@Configuration註解類上的@PropertySource
-
通過SpringApplication.setDefaultProperties指定的預設屬性
十一、自動配置原理
1.自動配置原理
1) SpringBoot啟動的時候載入主配置類,開啟了自動配置功能@EnableAutoConfiguration
2)@EnableAutoConfiguration的作用
-
利用AutoConfigurationImportSelector給容器匯入一些元件
-
可以檢視selectInports()方法的內容
-
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata)
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
SpringFactoriesLoader.loadFactoryNames()
掃描所有jar包類路徑下META-INF/spring.factories
把掃描到的這些檔案的內容包裝秤properties物件
從properties中獲取到EnableAutoConfiguration.class類對應的值
-
將類路徑下META-INF/spring.factories裡面配置的所有EnableAutoConfiguration的值加入到容器中
# Initializers org.springframework.context.ApplicationContextInitializer=\ org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\ org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener # Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.boot.autoconfigure.BackgroundPreinitializer # Auto Configuration Import Listeners org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\ org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener # Auto Configuration Import Filters org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ org.springframework.boot.autoconfigure.condition.OnBeanCondition,\ org.springframework.boot.autoconfigure.condition.OnClassCondition,\ org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition # 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.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\ 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.CassandraReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\ 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.r2dbc.R2dbcDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\ 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.ElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ 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.http.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\ org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\ 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.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\ org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\ 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.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\ org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\ 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.client.RestTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration # Failure analyzers org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\ org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\ org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\ org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\ org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\ org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer # Template availability providers org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\ org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\ org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\ org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
每一個這樣的xxxAutoCnfiguration類都是容器中的一個元件,都加入到容器中,用他們來做自動配置
3)、每一個自動配置類進行自動配置功能
4) 以HttpEncodingAutoConfiguration為例來解釋自動配置與案例
@Configuration( //表示這是一個配置類 可以給容器中新增元件
proxyBeanMethods = false
)
@EnableConfigurationProperties({ServerProperties.class}) //啟用指定類ConfigurationProperties功能 將配置檔案中對應的值和ConfigurationProperties繫結起來
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})//根據不同的條件,如果滿足指定的條件整改配置類裡面的配置就會生效 判斷當前專案有沒有CharacterEncodingFilter.class這個類
@ConditionalOnProperty(
prefix = "server.servlet.encoding",
value = {"enabled"},
matchIfMissing = true
)//判斷配置檔案中是否存在某個配置 server.servlet.encoding.enable=true如果不存在也是生效的
public class HttpEncodingAutoConfiguration {
private final Encoding properties;
//只有一個有參構造器的情況下,引數的值會從容器中拿
public HttpEncodingAutoConfiguration(ServerProperties properties) {
this.properties = properties.getServlet().getEncoding();
}
@Bean//給容器中新增元件 這個元件的某些值 需要從Properties中獲取
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
return filter;
}
根據當前不同的條件判斷,決定這個配置是否生效?
一旦這個配置類生效,這個配置類就會給容器中新增各種元件;這些元件的屬性是從對應的properties裡中獲取的,這些類裡面的屬性又是和配置檔案繫結的。
5)所有配置檔案中能配置的屬性都是在xxxProperties類中封裝著
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)//從配置檔案中獲取指定的值和bean的屬性進行繫結
public class ServerProperties {
精髓:
-
SpringBoot啟動會載入大量的自動配置類
-
我們看我們需要的功能有沒有SpringBoot預設寫好的自動配置類
-
我們再來看這個自動配置類到底配置了哪些元件
-
給容器中的自動配置類新增元件的時候,會從properties類中獲取某些屬性,我們就可以在配置檔案中指定這些屬性的至
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屬性,來讓控制檯列印自動配置報告
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches: (自動配置類啟用的)
-----------------
AopAutoConfiguration matched:
- @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
AopAutoConfiguration.ClassProxyingConfiguration matched:
- @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)
- @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)
Negative matches: (自動配置類沒有啟用的)
-----------------
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)
AopAutoConfiguration.AspectJAutoProxyingConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'org.aspectj.weaver.Advice' (OnClassCondition)