直接从 SpringBoot 程序入口的 run 方法看起:java
1 public static ConfigurableApplicationContext run(Object source, String... args) { 2 return run(new Object[] { source }, args); 3 }
执行第 2 行的 run(new Object[] { source }, args) 方法:react
1 public static ConfigurableApplicationContext run(Object[] sources, String[] args) { 2 return new SpringApplication(sources).run(args); 3 }
能够看到,这里启动其实是分为两步,先是建立 SpringApplication 对象,而后执行该对象的 run 方法。下面根据这两步进行深刻:web
下一步会进入 SpringApplication 类的构造方法:redis
1 public SpringApplication(Object... sources) { 2 initialize(sources); 3 }
接着进入 initialize 方法:spring
1 private void initialize(Object[] sources) { 2 if (sources != null && sources.length > 0) { 3 // 保存配置类,包含入口类 4 this.sources.addAll(Arrays.asList(sources)); 5 } 6 // 判断当前是不是一个 web 应用 7 this.webEnvironment = deduceWebEnvironment(); 8 // 从类路径下找到 META-INF/spring.factories 配置的全部 ApplicationContextInitializer 类并反射建立实例并保存到当前 SpringApplication 实例的 initializers 属性 9 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); 10 // 从类路径下找到 META-INF/spring.factories 配置的全部 ApplicationListener 类并反射建立实例保存到当前 SpringApplication 实例的 listeners 属性 11 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); 12 // 从调用栈中获取到执行了 main 方法的配置类即入口类保存到当前 SpringApplication 实例的 mainApplicationClass 属性 13 this.mainApplicationClass = deduceMainApplicationClass(); 14 }
在建立 SpringApplication 对象的过程当中实例化了类路径下 META-INF/spring.factories 中 ApplicationContextInitializer 节对应的应用上下文初始化器类和 ApplicationListener 节对应的应用监听器类并保存到了 SpringApplication 对象中。apache
能够看到在不少包中都有这个文件,下面为自动配置包中的 spring.factories 文件:springboot
# Initializers org.springframework.context.ApplicationContextInitializer=\ org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\ org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer # 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.OnClassCondition # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\ org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\ org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\ org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\ org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\ org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\ org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\ org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\ org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\ org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\ org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\ org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\ org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\ org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\ org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration # Failure analyzers org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\ org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\ org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer # 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.JspTemplateAvailabilityProvider
执行 org.springframework.boot.SpringApplication#run(java.lang.String...) 方法:websocket
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); // 声明一个 IoC 容器 ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; // AWT 相关 configureHeadlessProperty(); // 经过 getSpringFactoriesInstances 从类路径下找到 META-INF/spring.factories 配置的全部 SpringApplicationRunListener 类并反射建立实例返回 SpringApplicationRunListeners listeners = getRunListeners(args); // 回调执行全部 SpringApplicationRunListener 实例的 starting 方法 listeners.starting(); try { // 封装命令行参数 ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); // 准备环境,建立环境完成后在该方法中又回调执行了全部 SpringApplicationRunListener 实例的 environmentPrepared 方法,表示环境准备完成 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); // 控制台打印 SpringBoot 图标 Banner printedBanner = printBanner(environment); // 根据当前环境的不一样建立不一样类型的 IoC 容器 context = createApplicationContext(); // 初始化异常分析器 analyzers = new FailureAnalyzers(context); // 准备上下文环境: // 一、将 environment 保存到了 context 即 IoC 容器中 // 二、经过 applyInitializers(context) 方法,执行了全部 ApplicationContextInitializer 实例的 initialize(context) 方法(这些 ApplicationContextInitializer 实例是在初始化 SpringApplication 实例时建立保存的) // 三、还会回调执行全部 SpringApplicationRunListener 实例的 contextPrepared(context) 方法 // 四、在 prepareContext 方法最后一行还会回调执行全部 SpringApplicationRunListener 实例的 contextLoaded(context) 方法 prepareContext(context, environment, listeners, applicationArguments, printedBanner); // 刷新 IoC 容器,IoC 容器初始化,扫描、建立、加载全部组件(配置类、自动配置功能),若是是 web 应用,在这一步还会建立嵌入式 Servlet 容器 refreshContext(context); // 刷新后处理,会经过 callRunners(context, args) 方法从 IoC 容器中获取全部 ApplicationRunner 和 CommandLineRunner 的 bean,并回调它们的 run 方法 afterRefresh(context, applicationArguments); // 回调执行全部的 SpringApplicationRunListener 实例的 finished 方法,表示应用启动完成 listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } // 整个 SpringBoot 应用启动完成后返回 IoC 容器 return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
总结:session
在 SpringBoot 应用启动的过程当中会回调一些咱们预配置组件的指定方法,这些组件能够是咱们配置在指定文件中的类,也能够是咱们注册到 IoC 容器的 bean。分类以下:app
配置在 META-INF/spring.factories 中:
注册在 IoC 容器中:
执行的方法按回调顺序排序以下:
了解了 SpringBoot 程序的启动流程后,咱们也能够本身编写一个 starter 了,下面为一个小案例,功能是让程序在启动时注册一个 hello 组件,而且能经过配置修改输出内容。
一、使用 maven 建立一个 SpringBoot 程序做为自动配置组件,依赖以下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.19.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zze.springboot</groupId> <artifactId>mystarter_autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mystarter_autoconfigure</name> <description>Demo project for Spring Boot</description> <packaging>jar</packaging> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--引入 spring-boot-starter--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies> </project>
二、编写与配置文件属性映射的配置类:
package com.zze.springboot.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "com.zze") public class HelloProperties { private String name; private String remark; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
三、编写 hello 服务:
package com.zze.springboot.service; import com.zze.springboot.config.HelloProperties; public class HelloService { private HelloProperties helloProperties; public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public void sayHello() { System.out.println("hello " + helloProperties.getName() + " " + helloProperties.getRemark()); } }
四、编写自动配置类:
package com.zze.springboot.autoconfigure; import com.zze.springboot.config.HelloProperties; import com.zze.springboot.service.HelloService; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 自定义自动配置类 */ @EnableConfigurationProperties(HelloProperties.class) // 启用指定类的配置映射,并将配置类实例注册到 IoC 容器 @Configuration @ConditionalOnWebApplication // web 应用时才生效 public class MyStarterAutoConfiguration { private HelloProperties helloProperties; public MyStarterAutoConfiguration(HelloProperties helloProperties){ this.helloProperties = helloProperties; } // 注册 hello 服务到 IoC 容器 @Bean public HelloService helloService(){ HelloService helloService = new HelloService(); helloService.setHelloProperties(helloProperties); return helloService; } }
五、配置自动配置类,让程序启动时加载自动配置类让其生效:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zze.springboot.autoconfigure.MyStarterAutoConfiguration
一、建立普通的 maven 项目做为 starter 组件,引入上面编写的自动配置组件依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zze.springboot</groupId> <artifactId>mystarter</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--引入自动配置模块--> <dependency> <groupId>com.zze.springboot</groupId> <artifactId>mystarter_autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> </project>
二、将自动配置组件及 starter 组件安装到 maven 仓库。
一、使用 maven 新建立一个 SpringBoot 项目,引入咱们编写的 starter 依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.19.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.zze.springboot</groupId> <artifactId>mystarter</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
二、配置 hello 服务所须要的相关属性:
com.zze.name=张三
com.zze.remark=会员
三、直接注入 hello 服务,测试:
package com.example.demo; import com.zze.springboot.service.HelloService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired private HelloService helloService; @Test public void contextLoads() { helloService.sayHello(); /* hello 张三 会员 */ } }