Spring Boot启动原理解析(注解篇)

SpringBoot内置的自动配置使开发变得很方便,所以这次就来看看它的启动源码和它的自动化配置的实现原理。

    启动类:

 
  1. @SpringBootApplication

  2. public class DemoApplication {

  3.  
  4. public static void main(String[] args) {

  5. SpringApplication.run(DemoApplication.class, args);

  6. }

  7. }

    可以看到这个启动类中有两部分:@SpringBootApplicationSpringApplication.run(DemoApplication.class, args)两部分。每个Spring Boot项目都包含这两部分。

@SpringBootApplication

 
  1. @Target(ElementType.TYPE) // 注解的适用范围,TYPE用于描述类、接口、enum声明

  2. @Retention(RetentionPolicy.RUNTIME) // 注解的生命周期

  3. @Documented // 表明这个注解应该被javadoc记录

  4. @Inherited // 子类可以继承该注解

  5. @SpringBootConfiguration // 继承了Configuration,表示当前是注解类

  6. @EnableAutoConfiguration // 开启SpringBoot的注解功能,借助@import的帮助

  7. @ComponentScan(excludeFilters = { // 包扫描路径设置

  8. @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),

  9. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

  10. public @interface SpringBootApplication {

  11. ……

  12. }

这块最重要的三个注解是:

  • @Configuration:IoC容器的配置类(@SpringBootConfiguration内部有@Configuration)
  • @EnableAutoConfiguration:借助@Import的支持,将所有符合自动配置条件的bean定义加载到IoC容器。
  • @ComponentScan:自动扫描并加载符合条件的组件或者bean,最终将这些bean加载到IoC容器中

 这里主要研究下@EnableAutoConfiguration注解:

 
  1. @Target(ElementType.TYPE)

  2. @Retention(RetentionPolicy.RUNTIME)

  3. @Documented

  4. @Inherited

  5. @AutoConfigurationPackage

  6. @Import(AutoConfigurationImportSelector.class)

  7. public @interface EnableAutoConfiguration {

  8.  
  9. String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

  10.  
  11. ……

  12.  
  13. }

这个注解主要有两个注解组成:

  • @AutoConfigurationPackage:返回了当前主程序类的同级以及子级的包组件。
  • @Import(AutoConfigurationImportSelector.class):导入自动配置的组件

 先来看看@AutoConfigurationPackage的实现:

 
  1. @Target(ElementType.TYPE)

  2. @Retention(RetentionPolicy.RUNTIME)

  3. @Documented

  4. @Inherited

  5. @Import(AutoConfigurationPackages.Registrar.class)

  6. public @interface AutoConfigurationPackage {

  7.  
  8. }

  9.  
  10.  
  11. static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {

  12.  
  13. @Override

  14. public void registerBeanDefinitions(AnnotationMetadata metadata,

  15. BeanDefinitionRegistry registry) {

  16. register(registry, new PackageImport(metadata).getPackageName());

  17. }

  18.  
  19. @Override

  20. public Set<Object> determineImports(AnnotationMetadata metadata) {

  21. return Collections.singleton(new PackageImport(metadata));

  22. }

  23.  
  24. }

    它其实是注册了一个Bean的定义。new PackageImport(metadata).getPackageName(),它会返回当前主程序类的同级以及子级的包组件。

   这就是为什么要把主程序放在项目的顶层节点的原因。

下面再来看看@Import(AutoConfigurationImportSelector.class)的作用:

 
  1. public String[] selectImports(AnnotationMetadata annotationMetadata) {

  2. if (!isEnabled(annotationMetadata)) {

  3. return NO_IMPORTS;

  4. }

  5. AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader

  6. .loadMetadata(this.beanClassLoader);

  7. AnnotationAttributes attributes = getAttributes(annotationMetadata);

  8. List<String> configurations = getCandidateConfigurations(annotationMetadata,

  9. attributes);

  10. configurations = removeDuplicates(configurations);

  11. Set<String> exclusions = getExclusions(annotationMetadata, attributes);

  12. checkExcludedClasses(configurations, exclusions);

  13. configurations.removeAll(exclusions);

  14. configurations = filter(configurations, autoConfigurationMetadata);

  15. fireAutoConfigurationImportEvents(configurations, exclusions);

  16. return StringUtils.toStringArray(configurations);

  17. }

  18.  
  19.  
  20.  
  21. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,

  22. AnnotationAttributes attributes) {

  23. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(

  24. getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());

  25. Assert.notEmpty(configurations,

  26. "No auto configuration classes found in META-INF/spring.factories. If you "

  27. + "are using a custom packaging, make sure that file is correct.");

  28. return configurations;

  29. }

  30.  
  31.  
  32.  
  33. public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {

  34. String factoryClassName = factoryClass.getName();

  35. return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());

  36. }

  37.  
  38.  
  39.  
  40. private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {

  41. MultiValueMap<String, String> result = cache.get(classLoader);

  42. if (result != null) {

  43. return result;

  44. }

  45.  
  46. try {

  47. Enumeration<URL> urls = (classLoader != null ?

  48. classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :

  49. ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));

  50. result = new LinkedMultiValueMap<>();

  51. while (urls.hasMoreElements()) {

  52. URL url = urls.nextElement();

  53. UrlResource resource = new UrlResource(url);

  54. Properties properties = PropertiesLoaderUtils.loadProperties(resource);

  55. for (Map.Entry<?, ?> entry : properties.entrySet()) {

  56. List<String> factoryClassNames = Arrays.asList(

  57. StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));

  58. result.addAll((String) entry.getKey(), factoryClassNames);

  59. }

  60. }

  61. cache.put(classLoader, result);

  62. return result;

  63. }

  64. catch (IOException ex) {

  65. throw new IllegalArgumentException("Unable to load factories from location [" +

  66. FACTORIES_RESOURCE_LOCATION + "]", ex);

  67. }

  68. }

 

    可以看到它会从spring-boot-autoconfigure/2.0.2.RELEASE/spring-boot-autoconfigure-2.0.2.RELEASE.jar!/META-INF/spring.factories中去获取自动配置类,然后根据反射将其实例化为JavaConfig形式的IoC容器配置类,然后将其加载到IoC容器中。

 
  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.cloud.CloudAutoConfiguration,\

  9. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\

  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.ElasticsearchAutoConfiguration,\

  23. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\

  24. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\

  25. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\

  26. org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\

  27. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\

  28. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\

  29. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\

  30. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\

  31. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\

  32. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\

  33. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\

  34. org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\

  35. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\

  36. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\

  37. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\

  38. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\

  39. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\

  40. org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\

  41. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\

  42. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\

  43. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\

  44. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\

  45. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\

  46. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\

  47. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\

  48. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\

  49. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\

  50. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\

  51. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\

  52. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\

  53. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\

  54. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\

  55. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\

  56. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\

  57. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\

  58. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\

  59. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\

  60. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\

  61. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\

  62. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\

  63. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\

  64. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\

  65. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\

  66. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\

  67. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\

  68. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\

  69. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\

  70. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\

  71. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\

  72. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\

  73. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\

  74. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\

  75. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\

  76. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\

  77. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\

  78. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\

  79. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\

  80. org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\

  81. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\

  82. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\

  83. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\

  84. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\

  85. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\

  86. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\

  87. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\

  88. org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientAutoConfiguration,\

  89. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\

  90. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\

  91. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\

  92. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\

  93. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\

  94. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\

  95. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\

  96. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\

  97. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\

  98. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\

  99. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\

  100. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\

  101. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\

  102. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\

  103. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\

  104. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\

  105. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\

  106. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\

  107. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\

  108. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\

  109. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\

  110. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

执行流程篇:https://blog.csdn.net/qq_37598011/article/details/90969634

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值