spring boot 啟動類介紹
- spring boot項目啟動類代碼
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication.run(SystemApplication.class,args);
}
}
靜態(tài)方法run()堤瘤,是spring boot項目的啟動入口
- SpringBootApplication注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {}
- SpringApplication.run()
- @SpringBootConfiguration內(nèi)部用的也是@Configuration桑腮,它是javaConfig形式的Spring Ioc容器的配置類捌朴。
- @EnableAutoConfiguration
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}
借助@Import的支持洽损,注冊bean庞溜。@Import(EnableAutoConfigurationImportSelector.class)借助EnableAutoConfigurationImportSelector類,幫助springboot應(yīng)用將所有符合條件的@Configuration配置都加載到Ioc容器碑定,借助SpringFactoriesLoader工具類實現(xiàn)自動配置
- SpringFactoriesLoader其主要功能就是從指定的配置文件META-INF/spring.factories加載配置流码。將其中org.springframework.boot.autoconfigure.EnableutoConfiguration對應(yīng)的配置項通過反射(Java Refletion)實例化為對應(yīng)的標(biāo)注了@Configuration的JavaConfig形式的IoC容器配置類,然后匯總為一個并加載到IoC容器延刘。
脫離代碼的演示或講解都是流氓漫试,上代碼!5饫怠驾荣!
Spring Boot啟動流程
- 運行springboot啟動類
- 執(zhí)行SpringApplication.run()方法
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
- SpringApplication.run()靜態(tài)方法最終創(chuàng)建了一個SpringApplication對象,運行了其中的run方法
- SpringApplication的構(gòu)造方法設(shè)置基礎(chǔ)值
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.lazyInitialization = false;
//資源初始化加載器崖疤,默認(rèn)null
this.resourceLoader = resourceLoader;
//斷言主要加載資源類不能為null,否則報錯
Assert.notNull(primarySources, "PrimarySources must not be null");
//初始化主要加載資源類集合并去重
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
//判斷當(dāng)前WEB 應(yīng)用類型秘车,三種類型:NONE非web項目,SERVLET servlet web項目,REACTIVE 響應(yīng)式web項目
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//設(shè)置應(yīng)用上下文初始化器,從"MATE-INFO/spring.factories"讀取 ApplicationContextInitializer類的實例名稱集合并去重劫哼,并進行set去重叮趴。(一共7個)
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
//設(shè)置監(jiān)聽器,從"META-INF/spring.factories"讀取ApplicationListener類的實例名稱集合并去重,并進行set去重权烧。(一共11個)
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//推斷主入口應(yīng)用類眯亦,通過當(dāng)前調(diào)用棧伤溉,獲取Main方法所在類,并賦值給mainApplicationClass
this.mainApplicationClass = this.deduceMainApplicationClass();
}
public ConfigurableApplicationContext run(String... args) {
//1妻率、創(chuàng)建并啟動計時監(jiān)控類
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//2乱顾、初始化應(yīng)用上下文和異常報告集合
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//3、設(shè)置系統(tǒng)屬性“java.awt.headless”的值宫静,默認(rèn)為true走净,用于運行headless服務(wù)器,進行簡單的圖像處理孤里,多用于在缺少顯示屏伏伯、鍵盤或者鼠標(biāo)時的系統(tǒng)配置,很多監(jiān)控工具如jconsole 需要將該值設(shè)置為true
configureHeadlessProperty();
//4捌袜、創(chuàng)建所有spring運行監(jiān)聽器并發(fā)布應(yīng)用啟動事件说搅,簡單說的話就是獲取SpringApplicationRunListener類型的實例(EventPublishingRunListener對象),并封裝進SpringApplicationRunListeners對象虏等,然后返回這個SpringApplicationRunListeners對象弄唧。說的再簡單點,getRunListeners就是準(zhǔn)備好了運行時監(jiān)聽器EventPublishingRunListener霍衫。
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
//5候引、初始化默認(rèn)應(yīng)用參數(shù)類
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//6、根據(jù)運行監(jiān)聽器和應(yīng)用參數(shù)來準(zhǔn)備spring環(huán)境
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
//將要忽略的bean的參數(shù)打開
configureIgnoreBeanInfo(environment);
//7慕淡、創(chuàng)建banner打印類
Banner printedBanner = printBanner(environment);
//8背伴、創(chuàng)建應(yīng)用上下文,可以理解為創(chuàng)建一個容器
context = createApplicationContext();
//9峰髓、準(zhǔn)備異常報告器傻寂,用來支持報告關(guān)于啟動的錯誤
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
//10、準(zhǔn)備應(yīng)用上下文携兵,該步驟包含一個非常關(guān)鍵的操作疾掰,將啟動類注入容器,為后續(xù)開啟自動化提供基礎(chǔ)
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//11徐紧、刷新應(yīng)用上下文
refreshContext(context);
//12静檬、應(yīng)用上下文刷新后置處理,做一些擴展功能
afterRefresh(context, applicationArguments);
//13并级、停止計時監(jiān)控類
stopWatch.stop();
//14拂檩、輸出日志記錄執(zhí)行主類名、時間信息
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
//15嘲碧、發(fā)布應(yīng)用上下文啟動監(jiān)聽事件
listeners.started(context);
//16稻励、執(zhí)行所有的Runner運行器
callRunners(context, applicationArguments);
}catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
//17、發(fā)布應(yīng)用上下文就緒事件
listeners.running(context);
}catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
//18、返回應(yīng)用上下文
return context;
}