Blogger Information
Blog 41
fans 0
comment 0
visits 25296
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
11、【网摘】Spring Boot自动配置原理
自由之上
Original
514 people have browsed it

1、前言

我们知道,Spring Boot 项目创建完成后,即使不进行任何的配置,也能够顺利地运行,这都要归功于 Spring Boot 的自动化配置。
Spring Boot 默认使用 application.properties 或 application.yml 作为其全局配置文件,我们可以在该配置文件中对各种自动配置属性(server.port、logging.level.* 、spring.config.active.no-profile 等等)进行修改,并使之生效,那么您有没有想过这些属性是否有据可依呢?答案是肯定的。

Spring Boot 官方文档:常见应用属性中对所有的配置属性都进行了列举和解释,我们可以根据官方文档对 Spring Boot 进行配置,但 Spring Boot 中的配置属性数量庞大,仅仅依靠官方文档进行配置也十分麻烦。我们只有了解了 Spring Boot 自动配置的原理,才能更加轻松熟练地对 Spirng Boot 进行配置。本节为你揭开 SpringBoot 自动配置的神秘面纱。

2、Spring Factories 机制

Spring Boot 的自动配置是基于 Spring Factories 机制实现的。
Spring Factories 机制是 Spring Boot 中的一种服务发现机制,这种扩展机制与 Java SPI 机制十分相似。Spring Boot 会自动扫描所有 Jar 包类路径下 META-INF/spring.factories 文件,并读取其中的内容,进行实例化,这种机制也是 Spring Boot Starter 的基础。

1、spring.factories

spring.factories 文件本质上与 properties 文件相似,其中包含一组或多组键值对(key=vlaue),其中,key 的取值为接口的完全限定名;value 的取值为接口实现类的完全限定名,一个接口可以设置多个实现类,不同实现类之间使用“,”隔开,例如:

  1. org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=
  2. org.springframework.boot.autoconfigure.condition.OnBeanCondition,
  3. org.springframework.boot.autoconfigure.condition.OnClassCondition,
  4. org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

注意:文件中配置的内容过长,为了阅读方便而手动换行时,为了防止内容丢失可以使用“\”。

3、Spring Factories 实现原理

spring-core 包里定义了 SpringFactoriesLoader 类,这个类会扫描所有 Jar 包类路径下的 META-INF/spring.factories 文件,并获取指定接口的配置。在 SpringFactoriesLoader 类中定义了两个对外的方法,如下表。

以上两个方法的关键都是从指定的 ClassLoader 中获取 spring.factories 文件,并解析得到类名列表,具体代码如下。
loadFactories() 方法能够获取指定接口的实现类对象,具体代码如下。

  1. public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
  2. Assert.notNull(factoryType, "'factoryType' must not be null");
  3. ClassLoader classLoaderToUse = classLoader;
  4. if (classLoader == null) {
  5. classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
  6. }
  7. // 调用loadFactoryNames获取接口的实现类
  8. List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
  9. if (logger.isTraceEnabled()) {
  10. logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
  11. }
  12. // 遍历 factoryNames 数组,创建实现类的对象
  13. List<T> result = new ArrayList(factoryImplementationNames.size());
  14. Iterator var5 = factoryImplementationNames.iterator();
  15. //排序
  16. while(var5.hasNext()) {
  17. String factoryImplementationName = (String)var5.next();
  18. result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
  19. }
  20. AnnotationAwareOrderComparator.sort(result);
  21. return result;
  22. }

loadFactoryNames() 方法能够根据接口获取其实现类类名的集合,具体代码如下。

  1. public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
  2. ClassLoader classLoaderToUse = classLoader;
  3. if (classLoader == null) {
  4. classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
  5. }
  6. String factoryTypeName = factoryType.getName();
  7. //获取自动配置类
  8. return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
  9. }

loadSpringFactories() 方法能够读取该项目中所有 Jar 包类路径下 META-INF/spring.factories 文件的配置内容,并以 Map 集合的形式返回,具体代码如下。

  1. private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
  2. Map<String, List<String>> result = (Map)cache.get(classLoader);
  3. if (result != null) {
  4. return result;
  5. } else {
  6. HashMap result = new HashMap();
  7. try {
  8. //扫描所有 Jar 包类路径下的 META-INF/spring.factories 文件
  9. Enumeration urls = classLoader.getResources("META-INF/spring.factories");
  10. while(urls.hasMoreElements()) {
  11. URL url = (URL)urls.nextElement();
  12. UrlResource resource = new UrlResource(url);
  13. //将扫描到的 META-INF/spring.factories 文件中内容包装成 properties 对象
  14. Properties properties = PropertiesLoaderUtils.loadProperties(resource);
  15. Iterator var6 = properties.entrySet().iterator();
  16. while(var6.hasNext()) {
  17. Map.Entry<?, ?> entry = (Map.Entry)var6.next();
  18. //提取 properties 对象中的 key 值
  19. String factoryTypeName = ((String)entry.getKey()).trim();
  20. //提取 proper 对象中的 value 值(多个类的完全限定名使用逗号连接的字符串)
  21. // 使用逗号为分隔符转换为数组,数组内每个元素都是配置类的完全限定名
  22. String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
  23. String[] var10 = factoryImplementationNames;
  24. int var11 = factoryImplementationNames.length;
  25. //遍历配置类数组,并将数组转换为 list 集合
  26. for(int var12 = 0; var12 < var11; ++var12) {
  27. String factoryImplementationName = var10[var12];
  28. ((List)result.computeIfAbsent(factoryTypeName, (key) -> {
  29. return new ArrayList();
  30. })).add(factoryImplementationName.trim());
  31. }
  32. }
  33. }
  34. //将 propertise 对象的 key 与由配置类组成的 List 集合一一对应存入名为 result 的 Map 中
  35. result.replaceAll((factoryType, implementations) -> {
  36. return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
  37. });
  38. cache.put(classLoader, result);
  39. //返回 result
  40. return result;
  41. } catch (IOException var14) {
  42. throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
  43. }
  44. }
  45. }

4、自动配置的加载

Spring Boot 自动化配置也是基于 Spring Factories 机制实现的,在 spring-boot-autoconfigure-xxx.jar 类路径下的 META-INF/spring.factories 中设置了 Spring Boot 自动配置的内容 ,如下。

Auto Configure

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  2. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,
  3. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,
  4. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,
  5. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,
  6. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,
  7. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,
  8. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,
  9. org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,
  10. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,
  11. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,
  12. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,
  13. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,
  14. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,
  15. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,
  16. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,
  17. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,
  18. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,
  19. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,
  20. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,
  21. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,
  22. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,
  23. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,
  24. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,
  25. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,
  26. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,
  27. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,
  28. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,
  29. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,
  30. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,
  31. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,
  32. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,
  33. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,
  34. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,
  35. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,
  36. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,
  37. org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,
  38. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,
  39. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,
  40. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,
  41. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,
  42. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,
  43. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,
  44. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,
  45. org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,
  46. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,
  47. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,
  48. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,
  49. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,
  50. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,
  51. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,
  52. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,
  53. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,
  54. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,
  55. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,
  56. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,
  57. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,
  58. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,
  59. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,
  60. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,
  61. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,
  62. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,
  63. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,
  64. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,
  65. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,
  66. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,
  67. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,
  68. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,
  69. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,
  70. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,
  71. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,
  72. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,
  73. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,
  74. org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,
  75. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,
  76. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,
  77. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,
  78. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,
  79. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,
  80. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,
  81. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,
  82. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,
  83. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,
  84. org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,
  85. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,
  86. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,
  87. org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,
  88. org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,
  89. org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,
  90. org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,
  91. org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,
  92. org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,
  93. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,
  94. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,
  95. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,
  96. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,
  97. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,
  98. org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,
  99. org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,
  100. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,
  101. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,
  102. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,
  103. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,
  104. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,
  105. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,
  106. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,
  107. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,
  108. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,
  109. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,
  110. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,
  111. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,
  112. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,
  113. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,
  114. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,
  115. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,
  116. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,
  117. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,
  118. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,
  119. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,
  120. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,
  121. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,
  122. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,
  123. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,
  124. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,
  125. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,
  126. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,
  127. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,
  128. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,
  129. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,
  130. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,
  131. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

以上配置中,value 取值是由多个 xxxAutoConfiguration (使用逗号分隔)组成,每个 xxxAutoConfiguration 都是一个自动配置类。Spring Boot 启动时,会利用 Spring-Factories 机制,将这些 xxxAutoConfiguration 实例化并作为组件加入到容器中,以实现 Spring Boot 的自动配置。

5、@SpringBootApplication 注解

所有 Spring Boot 项目的主启动程序类上都使用了一个 @SpringBootApplication 注解,该注解是 Spring Boot 中最重要的注解之一 ,也是 Spring Boot 实现自动化配置的关键。
@SpringBootApplication 是一个组合元注解,其主要包含两个注解:@SpringBootConfiguration@EnableAutoConfiguration,其中 @EnableAutoConfiguration 注解是 SpringBoot 自动化配置的核心所在。

图1:@SpringBootApplication 注解

6、@EnableAutoConfiguration 注解

@EnableAutoConfiguration 注解用于开启 Spring Boot 的自动配置功能, 它使用 Spring 框架提供的 @Import 注解通过 AutoConfigurationImportSelector类(选择器)给容器中导入自动配置组件。

AutoConfigurationImportSelector 类
图2:@EnableAutoConfiguration 注解

7、AutoConfigurationImportSelector 类

AutoConfigurationImportSelector 类实现了 DeferredImportSelector 接口,AutoConfigurationImportSelector 中还包含一个静态内部类 AutoConfigurationGroup,它实现了 DeferredImportSelector 接口的内部接口 Group(Spring 5 新增)。
AutoConfigurationImportSelector 类中包含 3 个方法,如下表。

AutoConfigurationImportSelector 内各方法执行顺序如下。

  1. getImportGroup() 方法
  2. process() 方法
  3. selectImports() 方法

下面我们将分别对以上 3 个方法及其调用过程进行介绍。

1、getImportGroup() 方法

AutoConfigurationImportSelector 类中 getImportGroup() 方法主要用于获取实现了 DeferredImportSelector.Group 接口的类,代码如下。

  1. public Class<? extends Group> getImportGroup() {
  2. //获取实现了 DeferredImportSelector.Gorup 接口的 AutoConfigurationImportSelector.AutoConfigurationGroup 类
  3. return AutoConfigurationImportSelector.AutoConfigurationGroup.class;
  4. }

2、process() 方法

静态内部类 AutoConfigurationGroup 中的核心方法是 process(),该方法通过调用 getAutoConfigurationEntry() 方法读取 spring.factories 文件中的内容,获得自动配置类的集合,代码如下 。

  1. public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
  2. Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> {
  3. return String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName());
  4. });
  5. //拿到 META-INF/spring.factories中的EnableAutoConfiguration,并做排除、过滤处理
  6. //AutoConfigurationEntry里有需要引入配置类和排除掉的配置类,最终只要返回需要配置的配置类
  7. AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector)deferredImportSelector).getAutoConfigurationEntry(annotationMetadata);
  8. //加入缓存,List<AutoConfigurationEntry>类型
  9. this.autoConfigurationEntries.add(autoConfigurationEntry);
  10. Iterator var4 = autoConfigurationEntry.getConfigurations().iterator();
  11. while(var4.hasNext()) {
  12. String importClassName = (String)var4.next();
  13. //加入缓存,Map<String, AnnotationMetadata>类型
  14. this.entries.putIfAbsent(importClassName, annotationMetadata);
  15. }
  16. }

getAutoConfigurationEntry() 方法通过调用 getCandidateConfigurations() 方法来获取自动配置类的完全限定名,并在经过排除、过滤等处理后,将其缓存到成员变量中,具体代码如下。

  1. protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
  2. if (!this.isEnabled(annotationMetadata)) {
  3. return EMPTY_ENTRY;
  4. } else {
  5. //获取注解元数据中的属性设置
  6. AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
  7. //获取自动配置类
  8. List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
  9. //删除list 集合中重复的配置类
  10. configurations = this.removeDuplicates(configurations);
  11. //获取飘出导入的配置类
  12. Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
  13. //检查是否还存在排除配置类
  14. this.checkExcludedClasses(configurations, exclusions);
  15. //删除排除的配置类
  16. configurations.removeAll(exclusions);
  17. //获取过滤器,过滤配置类
  18. configurations = this.getConfigurationClassFilter().filter(configurations);
  19. //出发自动化配置导入事件
  20. this.fireAutoConfigurationImportEvents(configurations, exclusions);
  21. return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
  22. }
  23. }

在 getCandidateConfigurations() 方法中,根据 Spring Factories 机制调用 SpringFactoriesLoader 的 loadFactoryNames() 方法,根据 EnableAutoConfiguration.class (自动配置接口)获取其实现类(自动配置类)的类名的集合,如下图。

getCandidateConfigurations 方法
图3:getCandidateConfigurations 方法

3. selectImports() 方法

以上所有方法执行完成后,AutoConfigurationImportSelector.AutoConfigurationGroup#selectImports() 会将 process() 方法处理后得到的自动配置类,进行过滤、排除,最后将所有自动配置类添加到容器中。

  1. public Iterable<DeferredImportSelector.Group.Entry> selectImports() {
  2. if (this.autoConfigurationEntries.isEmpty()) {
  3. return Collections.emptyList();
  4. } else {
  5. //获取所有需要排除的配置类
  6. Set<String> allExclusions = (Set)this.autoConfigurationEntries.stream().
  7. map(AutoConfigurationImportSelector.AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
  8. //获取所有经过自动化配置过滤器的配置类
  9. Set<String> processedConfigurations = (Set)this.autoConfigurationEntries.stream().map(AutoConfigurationImportSelector.
  10. AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new));
  11. //排除过滤后配置类中需要排除的类
  12. processedConfigurations.removeAll(allExclusions);
  13. return (Iterable)this.sortAutoConfigurations(processedConfigurations,
  14. this.getAutoConfigurationMetadata()).stream().map((importClassName) -> {
  15. return new DeferredImportSelector.Group.Entry((AnnotationMetadata)this.entries.get(importClassName), importClassName);
  16. }).collect(Collectors.toList());
  17. }
  18. }

8、自动配置的生效和修改

spring.factories 文件中的所有自动配置类(xxxAutoConfiguration),都是必须在一定的条件下才会作为组件添加到容器中,配置的内容才会生效。这些限制条件在 Spring Boot 中以 @Conditional 派生注解的形式体现,如下表。

下面我们以 ServletWebServerFactoryAutoConfiguration 为例,介绍 Spring Boot 自动配置是如何生效的。

1、ServletWebServerFactoryAutoConfiguration

ServletWebServerFactoryAutoConfiguration 代码如下。

  1. @Configuration( //表示这是一个配置类,与 xml 配置文件等价,也可以给容器中添加组件
  2. proxyBeanMethods = false
  3. )
  4. @AutoConfigureOrder(-2147483648)
  5. @ConditionalOnClass({ServletRequest.class})//判断当前项目有没有 ServletRequest 这个类
  6. @ConditionalOnWebApplication(// 判断当前应用是否是 web 应用,如果是,当前配置类生效
  7. type = Type.SERVLET
  8. )
  9. @EnableConfigurationProperties({ServerProperties.class})
  10. //启动指定类的属性配置(ConfigurationProperties)功能;将配置文件中对应的值和 ServerProperties 绑定起来;并把 ServerProperties 加入到ioc容器中
  11. @Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
  12. public class ServletWebServerFactoryAutoConfiguration {
  13. public ServletWebServerFactoryAutoConfiguration() {
  14. }
  15. @Bean //给容器中添加一个组件,这个组件的某些值需要从properties中获取
  16. public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties, ObjectProvider<WebListenerRegistrar> webListenerRegistrars) {
  17. return new ServletWebServerFactoryCustomizer(serverProperties, (List) webListenerRegistrars.orderedStream().collect(Collectors.toList()));
  18. }
  19. @Bean
  20. @ConditionalOnClass(
  21. name = {"org.apache.catalina.startup.Tomcat"}
  22. )
  23. public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
  24. return new TomcatServletWebServerFactoryCustomizer(serverProperties);
  25. }
  26. @Bean
  27. @ConditionalOnMissingFilterBean({ForwardedHeaderFilter.class})
  28. @ConditionalOnProperty(
  29. value = {"server.forward-headers-strategy"},
  30. havingValue = "framework"
  31. )
  32. public FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
  33. ForwardedHeaderFilter filter = new ForwardedHeaderFilter();
  34. FilterRegistrationBean<ForwardedHeaderFilter> registration = new FilterRegistrationBean(filter, new ServletRegistrationBean[0]);
  35. registration.setDispatcherTypes(DispatcherType.REQUEST, new DispatcherType[]{DispatcherType.ASYNC, DispatcherType.ERROR});
  36. registration.setOrder(-2147483648);
  37. return registration;
  38. }
  39. public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
  40. private ConfigurableListableBeanFactory beanFactory;
  41. public BeanPostProcessorsRegistrar() {
  42. }
  43. public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  44. if (beanFactory instanceof ConfigurableListableBeanFactory) {
  45. this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
  46. }
  47. }
  48. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
  49. if (this.beanFactory != null) {
  50. this.registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);
  51. this.registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class, ErrorPageRegistrarBeanPostProcessor::new);
  52. }
  53. }
  54. private <T> void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<T> beanClass, Supplier<T> instanceSupplier) {
  55. if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) {
  56. RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass, instanceSupplier);
  57. beanDefinition.setSynthetic(true);
  58. registry.registerBeanDefinition(name, beanDefinition);
  59. }
  60. }
  61. }
  62. }

该类使用了以下注解:

  • @Configuration:用于定义一个配置类,可用于替换 Spring 中的 xml 配置文件;
  • @Bean:被 @Configuration 注解的类内部,可以包含有一个或多个被 @Bean 注解的方法,用于构建一个 Bean,并添加到 Spring 容器中;该注解与 spring 配置文件中 等价,方法名与 的 id 或 name 属性等价,方法返回值与 class 属性等价;

除了 @Configuration@Bean 注解外,该类还使用 5 个 @Conditional 衍生注解:

  • @ConditionalOnClass({ServletRequest.class}):判断当前项目是否存在 ServletRequest 这个类,若存在,则该配置类生效。
  • @ConditionalOnWebApplication(type = Type.SERVLET):判断当前应用是否是 Web 应用,如果是的话,当前配置类生效。
  • @ConditionalOnClass(name = {“org.apache.catalina.startup.Tomcat”}):判断是否存在 Tomcat 类,若存在则该方法生效。
  • @ConditionalOnMissingFilterBean({ForwardedHeaderFilter.class}):判断容器中是否有 ForwardedHeaderFilter 这个过滤器,若不存在则该方法生效。
  • @ConditionalOnProperty(value = {“server.forward-headers-strategy”},havingValue = “framework”):判断配置文件中是否存在 server.forward-headers-strategy = framework,若不存在则该方法生效。

2、ServerProperties

ServletWebServerFactoryAutoConfiguration 类还使用了一个 @EnableConfigurationProperties 注解,通过该注解导入了一个 ServerProperties 类,其部分源码如下。

  1. @ConfigurationProperties(
  2. prefix = "server",
  3. ignoreUnknownFields = true
  4. )
  5. public class ServerProperties {
  6. private Integer port;
  7. private InetAddress address;
  8. @NestedConfigurationProperty
  9. private final ErrorProperties error = new ErrorProperties();
  10. private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
  11. private String serverHeader;
  12. private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
  13. private Shutdown shutdown;
  14. @NestedConfigurationProperty
  15. private Ssl ssl;
  16. @NestedConfigurationProperty
  17. private final Compression compression;
  18. @NestedConfigurationProperty
  19. private final Http2 http2;
  20. private final ServerProperties.Servlet servlet;
  21. private final ServerProperties.Tomcat tomcat;
  22. private final ServerProperties.Jetty jetty;
  23. private final ServerProperties.Netty netty;
  24. private final ServerProperties.Undertow undertow;
  25. public ServerProperties() {
  26. this.shutdown = Shutdown.IMMEDIATE;
  27. this.compression = new Compression();
  28. this.http2 = new Http2();
  29. this.servlet = new ServerProperties.Servlet();
  30. this.tomcat = new ServerProperties.Tomcat();
  31. this.jetty = new ServerProperties.Jetty();
  32. this.netty = new ServerProperties.Netty();
  33. this.undertow = new ServerProperties.Undertow();
  34. }
  35. ....
  36. }

我们看到,ServletWebServerFactoryAutoConfiguration 使用了一个 @EnableConfigurationProperties 注解,而 ServerProperties 类上则使用了一个 @ConfigurationProperties 注解。这其实是 Spring Boot 自动配置机制中的通用用法。

Spring Boot 中为我们提供了大量的自动配置类 XxxAutoConfiguration 以及 XxxProperties,每个自动配置类 XxxAutoConfiguration 都使用了 @EnableConfigurationProperties 注解,而每个 XxxProperties 上都使用 @ConfigurationProperties 注解。

@ConfigurationProperties 注解的作用,是将这个类的所有属性与配置文件中相关的配置进行绑定,以便于获取或修改配置,但是 @ConfigurationProperties 功能是由容器提供的,被它注解的类必须是容器中的一个组件,否则该功能就无法使用。

@EnableConfigurationProperties 注解的作用正是将指定的类以组件的形式注入到 IOC 容器中,并开启其 @ConfigurationProperties 功能。

因此,@ConfigurationProperties + @EnableConfigurationProperties 组合使用,便可以为 XxxProperties 类实现配置绑定功能。

自动配置类 XxxAutoConfiguration 负责使用 XxxProperties 中属性进行自动配置,而 XxxProperties 则负责将自动配置属性与配置文件的相关配置进行绑定,以便于用户通过配置文件修改默认的自动配置。

也就是说,真正“限制”我们可以在配置文件中配置哪些属性的类就是这些 XxxxProperties 类,它与配置文件中定义的 prefix 关键字开头的一组属性是唯一对应的。

注意:XxxAutoConfiguration 与 XxxProperties 并不是一一对应的,大多数情况都是多对多的关系,即一个 XxxAutoConfiguration 可以同时使用多个 XxxProperties 中的属性,一个 XxxProperties 类中属性也可以被多个 XxxAutoConfiguration 使用。


加入
QQ群:722461036
微信群:
一起督促、学习、练习、温习、复习 ~ ~ ~

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post