分析SpringBoot底層機(jī)制
1.創(chuàng)建SpringBoot環(huán)境
(1)創(chuàng)建Maven程序,創(chuàng)建SpringBoot環(huán)境
(2)pom.xml導(dǎo)入SpringBoot的父工程和依賴(lài)
<!--導(dǎo)入SpringBoot父工程-規(guī)定寫(xiě)法--><parent><artifactId>spring-boot-starter-parent</artifactId><groupId>org.springframework.boot</groupId><version>2.5.3</version></parent><dependencies><!--導(dǎo)入web項(xiàng)目場(chǎng)景啟動(dòng)器:會(huì)自動(dòng)導(dǎo)入和web開(kāi)發(fā)相關(guān)的所有依賴(lài)[jar包]--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
(3)創(chuàng)建主程序MainApp.java
package com.li.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;/** * @author 李 * @version 1.0 *///表示SpringBoot項(xiàng)目public class MainApp {public static void main(String[] args) {//啟動(dòng)SpringBoot項(xiàng)目ConfigurableApplicationContext ioc =SpringApplication.run(MainApp.class, args);}}
(4)啟動(dòng)項(xiàng)目,我們可以注意到Tomcat也隨之啟動(dòng)了。

問(wèn)題一:當(dāng)我們執(zhí)行run方法時(shí),為什么會(huì)啟動(dòng)我們內(nèi)置的tomcat?它的底層是如何實(shí)現(xiàn)的?
2.Spring容器初始化(@Configuration+@Bean)
我們知道,如果在一個(gè)類(lèi)上添加了注解@Configuration,那么這個(gè)類(lèi)就會(huì)變成配置類(lèi);配置類(lèi)中通過(guò)@Bean注解,可以將方法中 new 出來(lái)的Bean對(duì)象注入到容器中,該bean對(duì)象的id默認(rèn)為方法名。
配置類(lèi)本身也會(huì)作為bean注入到容器中

?

容器初始化的底層機(jī)制仍然是我們之前分析的Spring容器的機(jī)制(IO/文件掃描+注解+反射+集合+映射)
對(duì)比:
Spring通過(guò)@ComponentScan,指定要掃描的包;而SpringBoot默認(rèn)從主程序所在的包開(kāi)始掃描,同時(shí)也可以指定要掃描的包(scanBasePackages = {"xxx.xx"})。
Spring通過(guò)xml或者注解,指定要注入的bean;SpringBoot通過(guò)掃描配置類(lèi)(對(duì)應(yīng)spring的xml)的@Bean或者注解,指定注入bean
3.SpringBoot怎樣啟動(dòng)Tomcat,并能支持訪問(wèn)@Controller?
由前面的例子1中可以看到,當(dāng)啟動(dòng)SpringBoot時(shí),tomcat也會(huì)隨之啟動(dòng)。那么問(wèn)題來(lái)了:
SpringBoot是怎么內(nèi)嵌Tomcat,并啟動(dòng)Tomcat的?
而且底層是怎樣讓@Controller修飾的控制器也可以被訪問(wèn)的?
3.1源碼分析SpringApplication.run()
SpringApplication.run()方法會(huì)完成兩個(gè)重要任務(wù):
創(chuàng)建容器
容器的刷新:包括參數(shù)的刷新+啟動(dòng)Tomcat
(1)創(chuàng)建一個(gè)控制器
package com.li.springboot.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author 李 * @version 1.0 * HiController被標(biāo)注后,作為一個(gè)控制器注入容器中 *///相當(dāng)于@Controller+@ResponseBodypublic class HiController {public String hi() {return "hi,HiController";}}
(2)啟動(dòng)主程序MainApp.java,進(jìn)行debug

(3)首先進(jìn)入SpringApplication.java的run方法

(4)點(diǎn)擊step into,進(jìn)入如下方法
public ConfigurableApplicationContext run(String... args) {...try {...context = this.createApplicationContext();//嚴(yán)重分析,創(chuàng)建容器context.setApplicationStartup(this.applicationStartup);this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);this.refreshContext(context);//刷新應(yīng)用上下文,比如初始化默認(rèn)設(shè)置/注入相關(guān)bean/啟動(dòng)Tomcatthis.afterRefresh(context, applicationArguments);stopWatch.stop();...} catch (Throwable var10) {...}...}
(5)分別對(duì) **createApplicationContext() **和?refreshContext(context)?方法進(jìn)行分析:
(5.1)step into 進(jìn)入 **createApplicationContext() ** 方法中:
//springApplication.java//容器類(lèi)型很多,會(huì)根據(jù)你的this.webApplicationType創(chuàng)建對(duì)應(yīng)的容器,默認(rèn)this.webApplicationType//的類(lèi)型為SERVLET,也就是web容器(可以處理servlet)protected ConfigurableApplicationContext createApplicationContext() {return this.applicationContextFactory.create(this.webApplicationType);}

(5.2)點(diǎn)擊進(jìn)入下一層
//接口 ApplicationContextFactory.java//該方法根據(jù)webApplicationType創(chuàng)建不同的容器ApplicationContextFactory DEFAULT = (webApplicationType) -> {try {switch(webApplicationType) {case SERVLET://默認(rèn)進(jìn)入這一分支,返回//AnnotationConfigServletWebServerApplicationContext容器return new AnnotationConfigServletWebServerApplicationContext();case REACTIVE:return new AnnotationConfigReactiveWebServerApplicationContext();default:return new AnnotationConfigApplicationContext();}} catch (Exception var2) {throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);}};
總結(jié):createApplicationContext()方法中創(chuàng)建了容器,但是還沒(méi)有將bean注入到容器中。
(5.3)step into 進(jìn)入?refreshContext(context)?方法中:
//springApplication.javaprivate void refreshContext(ConfigurableApplicationContext context) {if (this.registerShutdownHook) {shutdownHook.registerApplicationContext(context);}this.refresh(context);//核心,真正執(zhí)行相關(guān)任務(wù)}
(5.4)在this.refresh(context);這一步進(jìn)入下一層:
//springApplication.javaprotected void refresh(ConfigurableApplicationContext applicationContext) {applicationContext.refresh();}
(5.5)繼續(xù)進(jìn)入下一層:
protected void refresh(ConfigurableApplicationContext applicationContext) {applicationContext.refresh();}
(5.6)繼續(xù)進(jìn)入下一層:
//ServletWebServerApplicationContext.javapublic final void refresh() throws BeansException, IllegalStateException {try {super.refresh();} catch (RuntimeException var3) {WebServer webServer = this.webServer;if (webServer != null) {webServer.stop();}throw var3;}}
(5.7)在super.refresh();這一步進(jìn)入下一層:
//AbstractApplicationContext.javapublic void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");...try {...// Initialize other special beans in specific context subclasses.//在上下文的子類(lèi)初始化指定的beanonRefresh(); //當(dāng)父類(lèi)完成通用的工作后,再重新用動(dòng)態(tài)綁定機(jī)制回到子類(lèi)...}catch (BeansException ex) {...}finally {...}}}
(5.8)在onRefresh();這一步step into,會(huì)重新返回上一層:
//ServletWebServerApplicationContext.javaprotected void onRefresh() {super.onRefresh();try {this.createWebServer();//創(chuàng)建一個(gè)webserver,可以理解成創(chuàng)建我們指定的web服務(wù)-Tomcat} catch (Throwable var2) {throw new ApplicationContextException("Unable to start web server", var2);}}
(5.9)在this.createWebServer();這一步step into:
//ServletWebServerApplicationContext.javaprivate void createWebServer() {WebServer webServer = this.webServer;ServletContext servletContext = this.getServletContext();if (webServer == null && servletContext == null) {StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");ServletWebServerFactory factory = this.getWebServerFactory();createWebServer.tag("factory", factory.getClass().toString());this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});//使用TomcatServletWebServerFactory創(chuàng)建一個(gè)TomcatWebServercreateWebServer.end();this.getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));this.getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));} else if (servletContext != null) {try {this.getSelfInitializer().onStartup(servletContext);} catch (ServletException var5) {throw new ApplicationContextException("Cannot initialize servlet context", var5);}}this.initPropertySources();}

(5.10)在this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});這一步step into:
//TomcatServletWebServerFactory.java會(huì)創(chuàng)建Tomcat,并啟動(dòng)Tomcatpublic WebServer getWebServer(ServletContextInitializer... initializers) {if (this.disableMBeanRegistry) {Registry.disableRegistry();}Tomcat tomcat = new Tomcat();//創(chuàng)建了Tomcat對(duì)象,下面是一系列的初始化任務(wù)File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");tomcat.setBaseDir(baseDir.getAbsolutePath());Connector connector = new Connector(this.protocol);connector.setThrowOnFailure(true);tomcat.getService().addConnector(connector);this.customizeConnector(connector);tomcat.setConnector(connector);tomcat.getHost().setAutoDeploy(false);this.configureEngine(tomcat.getEngine());Iterator var5 = this.additionalTomcatConnectors.iterator();while(var5.hasNext()) {Connector additionalConnector = (Connector)var5.next();tomcat.getService().addConnector(additionalConnector);}this.prepareContext(tomcat.getHost(), initializers);return this.getTomcatWebServer(tomcat);}
(5.11)在return this.getTomcatWebServer(tomcat);這一步step into:
//TomcatServletWebServerFactory.java//這里做了端口校驗(yàn),創(chuàng)建了TomcatWebServerprotected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {return new TomcatWebServer(tomcat, this.getPort() >= 0, this.getShutdown());}
(5.12)繼續(xù)step into進(jìn)入下一層
//TomcatServletWebServerFactory.javapublic TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {this.monitor = new Object();this.serviceConnectors = new HashMap();Assert.notNull(tomcat, "Tomcat Server must not be null");this.tomcat = tomcat;this.autoStart = autoStart;this.gracefulShutdown = shutdown == Shutdown.GRACEFUL ? new GracefulShutdown(tomcat) : null;this.initialize();//進(jìn)行初始化,并啟動(dòng)tomcat}
(5.13)this.initialize();繼續(xù)step into:
//TomcatServletWebServerFactory.javaprivate void initialize() throws WebServerException {logger.info("Tomcat initialized with port(s): " + this.getPortsDescription(false));synchronized(this.monitor) {try {this.addInstanceIdToEngineName();Context context = this.findContext();context.addLifecycleListener((event) -> {if (context.equals(event.getSource()) && "start".equals(event.getType())) {this.removeServiceConnectors();}});this.tomcat.start();//啟動(dòng)Tomcat!this.rethrowDeferredStartupExceptions();try {ContextBindings.bindClassLoader(context, context.getNamingToken(), this.getClass().getClassLoader());} catch (NamingException var5) {}this.startDaemonAwaitThread();} catch (Exception var6) {this.stopSilently();this.destroySilently();throw new WebServerException("Unable to start embedded Tomcat", var6);}}}
(6)一路返回上層,然后終于執(zhí)行完refreshContext(context)方法,此時(shí)context為已經(jīng)注入了bean
