Spring Boot核心原理
spring-boot-starter-xxx 方便開發和配置
@SpringBootApplication //注解
public class Springbootdemo1Application {
public static void main(String[] args) {
//嚴格意義上執行的是這塊代碼
SpringApplication.run(Springbootdemo1Application.class, args);
}
}
一、 SpringBootApplication注解
注解的功能:參考https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/htmlsingle/#boot-documentation
除了元注解,還有三個注解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan( excludeFilters =
{@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
@SpringBootConfiguration 注解

讓我們當前的Bean叫給Spring容器進行管理(IOC),讓當前類變成配置類,不需要XML文件進行配置(配置類)。
EnableAutoConfiguration注解

@AutoConfigurationPackage
讓包中的類以及子包中的類能被自動掃描到Spring 容器中
@Import({AutoConfigurationImportSelector.class})
程序中默認使用的類幫我們找到
AutoConfigurationImportSelector類如下: 里面的selectImports里面,調用了getAutoConfigurationEntry方法。

getAutoConfigurationEntry方法中調用getCandidateConfigurations方法

getCandidateConfigurations方法使用的文件在META-INF/spring.factories

META-INF/spring.factories保存了系統默認加載進來的類。
這個文件的路徑如下圖:

@ComponentScan注解
通常它會結合@Coponent相關東西進行使用
總結:@SpringBootApplication
結合Spring MVC:
系統可能用到的Bean,幫我們放在了spring.factories 文件夾中
自己需要加載的bean, @Component結合@ComponentScan
二、 SpringApplication.run(Springbootdemo1Application.class, args);
程序啟動的時候執行這段代碼,
1、尋找內置的Tomcat執行的地方
this.refreshContext(context);
this.refresh(context);
((AbstractApplicationContext)applicationContext).refresh();
this.onRefresh()
onRefresh(ServletWebServerApplicationContext類中)
this.createWebServer();
factory.getWebServer
最終找到內置創建Tomcat的方法

2、@SpringBootApplicaton注解是如何准備類的? 如何理解spring.factories准備的類,然后拿到准備類去創建具體的對象?
SpringApplication.run(Springbootdemo1Application.class, args): 拿到准備類中的文件--> 具體創建對象
以下圖創建Tomcat實例為例

spring.factories中有一個與TomcatServletWebServerFactory相關的配置: ServletWebServerFactoryAutoConfiguration

ServletWebServerFactoryAutoConfiguration類如下

可以看到@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})。
然后進入EmbeddedTomcat類

自動配置:auto-configuration
注解在spring.factories中幫你維護好了所謂的全路徑
代碼執行的過程中你會用到的話,就會尋找對應的類

