微信公眾號:一個優秀的廢人。如有問題,請後臺留言,反正我也不會聽。
前言
這個月過去兩天了,這篇文章才跟大家見面,最近比較累,大家見諒下。下班後閒著無聊看了下 SpringBoot 中的自動配置,把我的理解跟大家說下。
配置檔案能寫什麼?
相信接觸過 SpringBoot 的朋友都知道 SpringBoot 有各種 starter 依賴,想要什麼直接勾選加進來就可以了。想要自定義的時候就直接在配置檔案寫自己的配置就好。但你們有沒有困惑,為什麼 SpringBoot 如此智慧,到底配置檔案裡面能寫什麼呢?
帶著這個疑問,我翻了下 SpringBoot 官網看到這麼一些配置樣例:
發現 SpringBoot 可配置的東西非常多,上圖只是節選。有興趣的檢視這個網址:
自動配置原理
這裡我拿之前建立過的 SpringBoot 來舉例講解 SpringBoot 的自動配置原理,首先看這麼一段程式碼:
@SpringBootApplication
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
}
複製程式碼
毫無疑問這裡只有 @SpringBootApplication 值得研究,進入 @SpringBootApplication 的原始碼:
SpringBoot 啟動的時候載入主配置類,開啟了自動配置功能 @EnableAutoConfiguration,再進入 @EnableAutoConfiguration 原始碼:
發現最重要的就是 @Import(AutoConfigurationImportSelector.class) 這個註解,其中的 AutoConfigurationImportSelector 類的作用就是往 Spring 容器中匯入元件,我們再進入這個類的原始碼,發現有這幾個方法:
/**
* 方法用於給容器中匯入元件
**/
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(
autoConfigurationMetadata, annotationMetadata); // 獲取自動配置項
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
// 獲取自動配置項
protected AutoConfigurationEntry getAutoConfigurationEntry(
AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List < String > configurations = getCandidateConfigurations(annotationMetadata,
attributes); // 獲取一個自動配置 List ,這個 List 就包含了所有自動配置的類名
configurations = removeDuplicates(configurations);
Set < String > exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
// 獲取一個自動配置 List ,這個 List 就包含了所有的自動配置的類名
protected List < String > getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
// 通過 getSpringFactoriesLoaderFactoryClass 獲取預設的 EnableAutoConfiguration.class 類名,傳入 loadFactoryNames 方法
List < String > configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), 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;
}
// 預設的 EnableAutoConfiguration.class 類名
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}
複製程式碼
程式碼註釋很清楚:
-
首先注意到 selectImports 方法,其實從方法名就能看出,這個方法用於給容器中匯入元件,然後跳到 getAutoConfigurationEntry 方法就是用於獲取自動配置項的。
-
再來進入 getCandidateConfigurations 方法就是 獲取一個自動配置 List ,這個 List 就包含了所有的自動配置的類名 。
-
再進入 SpringFactoriesLoader 類的 loadFactoryNames 方法,跳轉到 loadSpringFactories 方法發現 ClassLoader 類載入器指定了一個 FACTORIES_RESOURCE_LOCATION 常量。
-
然後利用PropertiesLoaderUtils 把 ClassLoader 掃描到的這些檔案的內容包裝成 properties 物件,從 properties 中獲取到 EnableAutoConfiguration.class 類(類名)對應的值,然後把他們新增在容器中。
public static List < String > loadFactoryNames(Class < ? > factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static Map < String, List < String >> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap < String, String > result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// 掃描所有 jar 包類路徑下 META-INF/spring.factories
Enumeration < URL > urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap < > ();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
// 把掃描到的這些檔案的內容包裝成 properties 物件
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry < ? , ? > entry : properties.entrySet()) {
String factoryClassName = ((String) entry.getKey()).trim();
for (String factoryName: StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
// 從 properties 中獲取到 EnableAutoConfiguration.class 類(類名)對應的值,然後把他們新增在容器中
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
複製程式碼
點選 FACTORIES_RESOURCE_LOCATION 常量,我發現它指定的是 jar 包類路徑下 META-INF/spring.factories 檔案:
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
複製程式碼
將類路徑下 META-INF/spring.factories 裡面配置的所有 EnableAutoConfiguration 的值加入到了容器中,所有的 EnableAutoConfiguration 如下所示:注意到 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.CloudServiceConnectorsAutoConfiguration,\
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.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.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
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.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.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
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.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.groovy.template.GroovyTemplateAutoConfiguration,\
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.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.reactor.core.ReactorCoreAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,\
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.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
複製程式碼
每一個這樣的 xxxAutoConfiguration 類都是容器中的一個元件,都加入到容器中,用他們來做自動配置。上述的每一個自動配置類都有自動配置功能,也可在配置檔案中自定義配置。
舉例說明 Http 編碼自動配置原理
@Configuration
// 表示這是一個配置類,以前編寫的配置檔案一樣,也可以給容器中新增元件
@EnableConfigurationProperties(HttpEncodingProperties.class)
// 啟動指定類的 ConfigurationProperties 功能;將配置檔案中對應的值和 HttpEncodingProperties 繫結起來;並把 HttpEncodingProperties 加入到 ioc 容器中
@ConditionalOnWebApplication
// Spring 底層 @Conditional 註解,根據不同的條件,如果滿足指定的條件,整個配置類裡面的配置就會生效;判斷當前應用是否是 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;
}
複製程式碼
自動配置類做了什麼不在這裡贅述,請見上面程式碼。所有在配置檔案中能配置的屬性都是在 xxxxProperties 類中封裝的;配置檔案能配置什麼就可以參照某個功能對應的這個屬性類,例如上述提到的 @EnableConfigurationProperties(HttpProperties.class) ,我們開啟 HttpProperties 檔案原始碼節選:
@ConfigurationProperties(prefix = "spring.http")
public class HttpProperties {
public static class Encoding {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* Charset of HTTP requests and responses. Added to the "Content-Type" header if
* not set explicitly.
*/
private Charset charset = DEFAULT_CHARSET;
/**
* Whether to force the encoding to the configured charset on HTTP requests and
* responses.
*/
private Boolean force;
}
複製程式碼
在上面可以發現裡面的屬性 charset 、force 等,都是我們可以在配置檔案中指定的,它的字首就是 spring.http.encoding 如:
另外,如果配置檔案中有配該屬性就取配置檔案的,若無就使用 XxxxProperties.class 檔案的預設值,比如上述程式碼的 Charset 屬性,如果不配那就使用 UTF-8 預設值。
總結
1. SpringBoot 啟動會載入大量的自動配置類
2. 我們看我們需要的功能有沒有 SpringBoot 預設寫好的自動配置類;
3. 我們再來看這個自動配置類中到底配置了哪些元件 ( 只要我們要用的元件有,我們就不需要再來配置,若沒有,我們可能就要考慮自己寫一個配置類讓 SpringBoot 掃描了)
4. 給容器中自動配置類新增元件的時候,會從 properties 類中獲取某些屬性。我們就可以在配置檔案中指定這些屬性的值;
xxxxAutoConfigurartion 自動配置類的作用就是給容器中新增元件
xxxxProperties 的作用就是封裝配置檔案中相關屬性
至此,總算弄明白了 SpringBoot 的自動配置原理。我水平優先,如有不當之處,敬請指出,相互交流學習,希望對你們有幫助。
後語
如果本文對你哪怕有一丁點幫助,請幫忙點好看。你的好看是我堅持寫作的動力。
另外,關注之後在傳送 1024 可領取免費學習資料。
資料詳情請看這篇舊文:Python、C++、Java、Linux、Go、前端、演算法資料分享