1. 程式人生 > >springboot原始碼解析-管中窺豹系列之總體結構(一)

springboot原始碼解析-管中窺豹系列之總體結構(一)

# 一、簡介 - Springboot原始碼解析是一件大工程,逐行逐句的去研究程式碼,會很枯燥,也不容易堅持下去。 - 我們不追求大而全,而是試著每次去研究一個小知識點,最終聚沙成塔,這就是我們的springboot原始碼管中窺豹系列。 ![ 簡介 ](https://zhangbin1989.gitee.io/blog/picture/zb0018_springsour/springboot_source_0.png) # 二、框架 我們先把springboot原始碼的框架了解清楚。 ## 1、新建一個springboot專案 ``` import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyprojectApplication { public static void main(String[] args) { SpringApplication.run(MyprojectApplication.class, args); } } ``` ## 2、分析原始碼 相比於spring專案或者springmvc專案,springboot的入口很好找,就在main裡面的run方法,我們進入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的靜態方法,新建了一個SpringApplication類,呼叫它的run方法,我們先看SpringApplication的構造方法,再看run方法 ``` public SpringApplication(Class... primarySources) { this(null, primarySources); } @SuppressWarnings({ "unchecked", "rawtypes" }) public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) { this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } ``` 構造方法主要做了這幾件事: - 確定web型別:webApplicationType - 載入ApplicationContextInitializer - 載入ApplicationListener - 確定applicationcontext的實現類 實現細節我們先不探討,接著看run方法 ``` public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection