分析SpringBoot底層機制
Tomcat啟動分析,Spring容器初始化,Tomcat如何關聯Spring容器?
1.創建SpringBoot環境
(1)創建Maven程式,創建SpringBoot環境
(2)pom.xml匯入SpringBoot的父工程和依賴
<!--匯入SpringBoot父工程-規定寫法-->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.5.3</version>
</parent>
<dependencies>
<!--匯入web專案場景啟動器:會自動匯入和web開發相關的所有依賴[jar包]-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
(3)創建主程式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
*/
@SpringBootApplication//表示SpringBoot專案
public class MainApp {
public static void main(String[] args) {
//啟動SpringBoot專案
ConfigurableApplicationContext ioc =
SpringApplication.run(MainApp.class, args);
}
}
(4)啟動專案,我們可以注意到Tomcat也隨之啟動了,
問題一:當我們執行run方法時,為什么會啟動我們內置的tomcat?它的底層是如何實作的?
2.Spring容器初始化(@Configuration+@Bean)
我們知道,如果在一個類上添加了注解@Configuration,那么這個類就會變成配置類;配置類中通過@Bean注解,可以將方法中 new 出來的Bean物件注入到容器中,該bean物件的id默認為方法名,
配置類本身也會作為bean注入到容器中
容器初始化的底層機制仍然是我們之前分析的Spring容器的機制(IO/檔案掃描+注解+反射+集合+映射)
對比:
- Spring通過@ComponentScan,指定要掃描的包;而SpringBoot默認從主程式所在的包開始掃描,同時也可以指定要掃描的包(scanBasePackages = {"xxx.xx"}),
- Spring通過xml或者注解,指定要注入的bean;SpringBoot通過掃描配置類(對應spring的xml)的@Bean或者注解,指定注入bean
3.SpringBoot怎樣啟動Tomcat,并能支持訪問@Controller?
由前面的例子1中可以看到,當啟動SpringBoot時,tomcat也會隨之啟動,那么問題來了:
- SpringBoot是怎么內嵌Tomcat,并啟動Tomcat的?
- 而且底層是怎樣讓@Controller修飾的控制器也可以被訪問的?
3.1原始碼分析SpringApplication.run()
SpringApplication.run()方法會完成兩個重要任務:
- 創建容器
- 容器的重繪:包括引數的重繪+啟動Tomcat
(1)創建一個控制器
package com.li.springboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 李
* @version 1.0
* HiController被標注后,作為一個控制器注入容器中
*/
@RestController//相當于@Controller+@ResponseBody
public class HiController {
@RequestMapping("/hi")
public String hi() {
return "hi,HiController";
}
}
(2)啟動主程式MainApp.java,進行debug
(3)首先進入SpringApplication.java的run方法
(4)點擊step into,進入如下方法
public ConfigurableApplicationContext run(String... args) {
...
try {
...
context = this.createApplicationContext();//嚴重分析,創建容器
context.setApplicationStartup(this.applicationStartup);
this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);//重繪應用背景關系,比如初始化默認設定/注入相關bean/啟動Tomcat
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
...
} catch (Throwable var10) {...}
...
}
(5)分別對 **createApplicationContext() **和 refreshContext(context) 方法進行分析:
(5.1)step into 進入 **createApplicationContext() ** 方法中:
//springApplication.java
//容器型別很多,會根據你的this.webApplicationType創建對應的容器,默認this.webApplicationType
//的型別為SERVLET,也就是web容器(可以處理servlet)
protected ConfigurableApplicationContext createApplicationContext() {
return this.applicationContextFactory.create(this.webApplicationType);
}
(5.2)點擊進入下一層
//介面 ApplicationContextFactory.java
//該方法根據webApplicationType創建不同的容器
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
try {
switch(webApplicationType) {
case SERVLET://默認進入這一分支,回傳
//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);
}
};
總結:createApplicationContext()方法中創建了容器,但是還沒有將bean注入到容器中,
(5.3)step into 進入 refreshContext(context) 方法中:
//springApplication.java
private void refreshContext(ConfigurableApplicationContext context) {
if (this.registerShutdownHook) {
shutdownHook.registerApplicationContext(context);
}
this.refresh(context);//核心,真正執行相關任務
}
(5.4)在this.refresh(context);這一步進入下一層:
//springApplication.java
protected void refresh(ConfigurableApplicationContext applicationContext) {
applicationContext.refresh();
}
(5.5)繼續進入下一層:
protected void refresh(ConfigurableApplicationContext applicationContext) {
applicationContext.refresh();
}
(5.6)繼續進入下一層:
//ServletWebServerApplicationContext.java
public 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();這一步進入下一層:
//AbstractApplicationContext.java
@Override
public 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.
//在背景關系的子類初始化指定的bean
onRefresh(); //當父類完成通用的作業后,再重新用動態系結機制回到子類
...
}
catch (BeansException ex) {...}
finally {...}
}
}
(5.8)在onRefresh();這一步step into,會重新回傳上一層:
//ServletWebServerApplicationContext.java
protected void onRefresh() {
super.onRefresh();
try {
this.createWebServer();//創建一個webserver,可以理解成創建我們指定的web服務-Tomcat
} catch (Throwable var2) {
throw new ApplicationContextException("Unable to start web server", var2);
}
}
(5.9)在this.createWebServer();這一步step into:
//ServletWebServerApplicationContext.java
private 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創建一個TomcatWebServer
createWebServer.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會創建Tomcat,并啟動Tomcat
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();//創建了Tomcat物件,下面是一系列的初始化任務
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
//這里做了埠校驗,創建了TomcatWebServer
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
return new TomcatWebServer(tomcat, this.getPort() >= 0, this.getShutdown());
}
(5.12)繼續step into進入下一層
//TomcatServletWebServerFactory.java
public 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();//進行初始化,并啟動tomcat
}
(5.13)this.initialize();繼續step into:
//TomcatServletWebServerFactory.java
private 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();//啟動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)一路回傳上層,然后終于執行完refreshContext(context)方法,此時context為已經注入了bean
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/546786.html
標籤:Java
