作者:李巖科
1 背景
SpringBoot 是一個框架,一種全新的編程規范,他的產生簡化了框架的使用,同時也提供了很多便捷的功能,比如內置 tomcat 就是其中一項,他讓我們省去了搭建 tomcat 容器,生成 war,部署,啟動 tomcat,因為內置了啟動容器,應用程式可以直接通過 Maven 命令將專案編譯成可執行的 jar 包,通過 java -jar 命令直接啟動,不需要再像以前一樣,打包成 War 包,然后部署在 Tomcat 中,那么內置 tomcat 是如何實作的呢
2 tomcat 啟動程序及原理
2.1 下載一個 springboot 專案
在這里下載一個專案 https://start.spring.io/ 也可以在 idea 新建 SpringBoot-Web 工程.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
點擊 pom.xml 會有 tomcat 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
2.2 從啟動入口開始一步步探索
點擊進入 run 方法
public static ConfigurableApplicationContext run(Class<?> primarySource,
String... args) {
return run(new Class<?>[] { primarySource }, args);
}
//繼續點擊進入run方法
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
進入到這個 run 方法之后就可以看到,我們認識的一些初始化事件,主要的程序也是在這里完成的,
2.3 原始碼代碼流程大致是這樣
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
/**1、配置系統屬性*/
configureHeadlessProperty();
/**2.獲取監聽器*/
SpringApplicationRunListeners listeners = getRunListeners(args);
/**發布應用開始啟動事件 */
listeners.starting();
try {
/** 3.初始化引數 */
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
/** 4.配置環境*/
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
/**5.創建應用背景關系*/
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
/**6.預處理背景關系*/
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
/**6.重繪背景關系*/
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
/** 8.發布應用已經啟動事件 */
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
/** 9.發布應用已經啟動完成的監聽事件 */
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
代碼中主要就是通過 switch 陳述句,根據 webApplicationType 的型別來創建不同的 ApplicationContext:
- DEFAULT_SERVLET_WEB_CONTEXT_CLASS:Web 型別,實體化 AnnotationConfigServletWebServerApplicationContext
- DEFAULT_REACTIVE_WEB_CONTEXT_CLASS:回應式 Web 型別,實體化 AnnotationConfigReactiveWebServerApplicationContext
- DEFAULT_CONTEXT_CLASS:非 Web 型別,實體化 AnnotationConfigApplicationContext
2.4 創建完應用背景關系之后,我們在看重繪背景關系方法
一步步通過斷點點擊方法進去查看,我們看到很熟悉代碼 spring 的相關代碼,
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//初始化前的準備作業,主要是一些系統屬性、環境變數的校驗,比如Spring啟動需要某些環境變數,可以在這個地方進行設定和校驗
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//準備bean工廠 注冊了部分類
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//注冊bean工廠后置處理器,并決議java代碼配置bean定義
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注冊bean后置處理器,并不會執行后置處理器,在后面實體化的時候執行
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
//初始化事件監聽多路廣播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//待子類實作,springBoot在這里實作創建內置的tomact容器
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
2.5 onRefresh () 方法是呼叫其子類實作的
也就是 ServletWebServerApplicationContext
/** 得到Servlet工廠 **/
this.webServer = factory.getWebServer(getSelfInitializer());
其中 createWebServer () 方法是用來啟動 web 服務的,但是還沒有真正啟動 Tomcat,只是通過 ServletWebServerFactory 創建了一個 WebServer,繼續來看這個 ServletWebServerFactory:
this.webServer = factory.getWebServer (getSelfInitializer ()); 這個方法可以看出 TomcatServletWebServerFactory 的實作,相關 Tomcat 的實作,
2.6 TomcatServletWebServerFactory 的 getWebServer () 方法
清晰的看到 new 出來了一個 Tomcat.
2.7 Tomcat 創建之后,繼續分析 Tomcat 的相關設定和引數
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
/** 1、創建Tomcat實體 **/
Tomcat tomcat = new Tomcat();
//創建Tomcat作業目錄
File baseDir = (this.baseDirectory != null) ? this.baseDirectory
: createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
/** 2、給創建好的tomcat設定連接器connector **/
tomcat.setConnector(connector);
/** 3.設定不自動部署 **/
tomcat.getHost().setAutoDeploy(false);
/** 4.配置Tomcat容器引擎 **/
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
/**準備Tomcat的StandardContext,并添加到Tomcat中*/
prepareContext(tomcat.getHost(), initializers);
/** 將創建好的Tomcat包裝成WebServer回傳**/
return getTomcatWebServer(tomcat);
}
2.8 繼續點擊 getTomcatWebServer 方法,找到 initialize () 方法,可以看到 tomcat.start (); 啟動 tomcat 服務方法,
// Start the server to trigger initialization listeners
//啟動tomcat服務
this.tomcat.start();
//開啟阻塞非守護行程
startDaemonAwaitThread();
//Tomcat.java
2.9 TomcatWebServer.java 控制臺會列印這句話
Tomcat started on port(s): 8080 (http) with context path ‘’
3 總結
SpringBoot 的啟動主要是通過實體化 SpringApplication 來啟動的,啟動程序主要做了如下幾件事情:
配置系統屬性、獲取監聽器,發布應用開始啟動事件、初始化引數、配置環境、創建應用背景關系、預處理背景關系、重繪背景關系、再次重繪背景關系、發布應用已經啟動事件、發布應用啟動完成事件,而啟動 Tomcat 是重繪背景關系 這一步,
Spring Boot 創建 Tomcat 時,會先創建一個背景關系,將 WebApplicationContext 傳給 Tomcat;
啟動 Web 容器,需要呼叫 getWebserver (),因為默認的 Web 環境就是 TomcatServletWebServerFactory,所以會創建 Tomcat 的 Webserver,這里會把根背景關系作為引數給 TomcatServletWebServerFactory 的 getWebServer ();啟動 Tomcat,呼叫 Tomcat 中 Host、Engine 的啟動方法,
3.1 Tomcat 相關名稱介紹
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/539710.html
標籤:其他
下一篇:經典排序演算法
