javascript
class没有发布到tomcat_面试官扎心一问:Tomcat 在 SpringBoot 中是如何启动的?
作者:木木匠?
my.oschina.net/luozhou/blog/3088908
前言
我們知道 SpringBoot 給我們帶來了一個(gè)全新的開發(fā)體驗(yàn),我們可以直接把 web 程序達(dá)成 jar 包,直接啟動(dòng),這就得益于 SpringBoot 內(nèi)置了容器,可以直接啟動(dòng),本文將以 Tomcat 為例,來看看 SpringBoot 是如何啟動(dòng) Tomcat 的,同時(shí)也將展開學(xué)習(xí)下 Tomcat 的源碼,了解 Tomcat 的設(shè)計(jì)。
從 Main 方法說起
用過 SpringBoot 的人都知道,首先要寫一個(gè) main 方法來啟動(dòng)
@SpringBootApplicationpublic class TomcatdebugApplication {public static void main(String[] args) {
SpringApplication.run(TomcatdebugApplication.class, args);
}
}
我們直接點(diǎn)擊 run 方法的源碼,跟蹤下來,發(fā)下最終的 run 方法是調(diào)用 ConfigurableApplicationContext 方法,源碼如下:
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection exceptionReporters = new ArrayList> //設(shè)置系統(tǒng)屬性『java.awt.headless』,為true則啟用headless模式支持
configureHeadlessProperty();//通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,//找到聲明的所有SpringApplicationRunListener的實(shí)現(xiàn)類并將其實(shí)例化,//之后逐個(gè)調(diào)用其started()方法,廣播SpringBoot要開始執(zhí)行了
SpringApplicationRunListeners listeners = getRunListeners(args);//發(fā)布應(yīng)用開始啟動(dòng)事件
listeners.starting();try {//初始化參數(shù)
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);//創(chuàng)建并配置當(dāng)前SpringBoot應(yīng)用將要使用的Environment(包括配置要使用的PropertySource以及Profile),//并遍歷調(diào)用所有的SpringApplicationRunListener的environmentPrepared()方法,廣播Environment準(zhǔn)備完畢。
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);//打印banner
Banner printedBanner = printBanner(environment);//創(chuàng)建應(yīng)用上下文
context = createApplicationContext();//通過*SpringFactoriesLoader*檢索*META-INF/spring.factories*,獲取并實(shí)例化異常分析器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);//為ApplicationContext加載environment,之后逐個(gè)執(zhí)行ApplicationContextInitializer的initialize()方法來進(jìn)一步封裝ApplicationContext,//并調(diào)用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一個(gè)空的contextPrepared()方法】,//之后初始化IoC容器,并調(diào)用SpringApplicationRunListener的contextLoaded()方法,廣播ApplicationContext的IoC加載完成,//這里就包括通過**@EnableAutoConfiguration**導(dǎo)入的各種自動(dòng)配置類。
prepareContext(context, environment, listeners, applicationArguments, printedBanner);//刷新上下文
refreshContext(context);//再一次刷新上下文,其實(shí)是空方法,可能是為了后續(xù)擴(kuò)展。
afterRefresh(context, applicationArguments);
stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}//發(fā)布應(yīng)用已經(jīng)啟動(dòng)的事件
listeners.started(context);//遍歷所有注冊的ApplicationRunner和CommandLineRunner,并執(zhí)行其run()方法。//我們可以實(shí)現(xiàn)自己的ApplicationRunner或者CommandLineRunner,來對(duì)SpringBoot的啟動(dòng)過程進(jìn)行擴(kuò)展。
callRunners(context, applicationArguments);
}catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);throw new IllegalStateException(ex);
}try {//應(yīng)用已經(jīng)啟動(dòng)完成的監(jiān)聽事件
listeners.running(context);
}catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);throw new IllegalStateException(ex);
}return context;
}
其實(shí)這個(gè)方法我們可以簡單的總結(jié)下步驟為 > 1. 配置屬性 > 2. 獲取監(jiān)聽器,發(fā)布應(yīng)用開始啟動(dòng)事件 > 3. 初始化輸入?yún)?shù) > 4. 配置環(huán)境,輸出 banner > 5. 創(chuàng)建上下文 > 6. 預(yù)處理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 發(fā)布應(yīng)用已經(jīng)啟動(dòng)事件 > 10. 發(fā)布應(yīng)用啟動(dòng)完成事件
其實(shí)上面這段代碼,如果只要分析 tomcat 內(nèi)容的話,只需要關(guān)注兩個(gè)內(nèi)容即可,上下文是如何創(chuàng)建的,上下文是如何刷新的,分別對(duì)應(yīng)的方法就是 createApplicationContext() 和 refreshContext(context),接下來我們來看看這兩個(gè)方法做了什么。
protected ConfigurableApplicationContext createApplicationContext() {
Class contextClass = this.applicationContextClass;if (contextClass == null) {try {switch (this.webApplicationType) {case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);break;case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);break;default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}catch (ClassNotFoundException ex) {throw new IllegalStateException("Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass",
ex);
}
}return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
這里就是根據(jù)我們的 webApplicationType 來判斷創(chuàng)建哪種類型的 Servlet,代碼中分別對(duì)應(yīng)著 Web 類型(SERVLET),響應(yīng)式 Web 類型(REACTIVE),非 Web 類型(default),我們建立的是 Web 類型,所以肯定實(shí)例化 DEFAULT_SERVLET_WEB_CONTEXT_CLASS 指定的類,也就是 AnnotationConfigServletWebServerApplicationContext 類,我們來用圖來說明下這個(gè)類的關(guān)系
通過這個(gè)類圖我們可以知道,這個(gè)類繼承的是 ServletWebServerApplicationContext,這就是我們真正的主角,而這個(gè)類最終是繼承了 AbstractApplicationContext,了解完創(chuàng)建上下文的情況后,我們再來看看刷新上下文,相關(guān)代碼如下:
//類:SpringApplication.javaprivate void refreshContext(ConfigurableApplicationContext context) {//直接調(diào)用刷新方法
refresh(context);if (this.registerShutdownHook) {try {
context.registerShutdownHook();
}catch (AccessControlException ex) {// Not allowed in some environments.
}
}
}//類:SpringApplication.javaprotected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
這里還是直接傳遞調(diào)用本類的 refresh(context)方法,最后是強(qiáng)轉(zhuǎn)成父類 AbstractApplicationContext 調(diào)用其 refresh()方法,該代碼如下:
// 類:AbstractApplicationContextpublic void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.
prepareRefresh();// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);// Initialize message source for this context.
initMessageSource();// Initialize event multicaster for this context.
initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.這里的意思就是調(diào)用各個(gè)子類的onRefresh()
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();
}
}
}
這里我們看到 onRefresh()方法是調(diào)用其子類的實(shí)現(xiàn),根據(jù)我們上文的分析,我們這里的子類是 ServletWebServerApplicationContext。
//類:ServletWebServerApplicationContextprotected void onRefresh() {super.onRefresh();try {
createWebServer();
}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);
}
}private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();this.webServer = factory.getWebServer(getSelfInitializer());
}else if (servletContext != null) {try {
getSelfInitializer().onStartup(servletContext);
}catch (ServletException ex) {throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
到這里,其實(shí)廬山真面目已經(jīng)出來了,createWebServer()就是啟動(dòng) web 服務(wù),但是還沒有真正啟動(dòng) Tomcat,既然 webServer 是通過 ServletWebServerFactory 來獲取的,我們就來看看這個(gè)工廠的真面目。
走進(jìn) Tomcat 內(nèi)部
根據(jù)上圖我們發(fā)現(xiàn),工廠類是一個(gè)接口,各個(gè)具體服務(wù)的實(shí)現(xiàn)是由各個(gè)子類來實(shí)現(xiàn)的,所以我們就去看看 TomcatServletWebServerFactory.getWebServer()的實(shí)現(xiàn)。
@Overridepublic WebServer getWebServer(ServletContextInitializer... initializers) {
Tomcat tomcat = new 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);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);return getTomcatWebServer(tomcat);
}
根據(jù)上面的代碼,我們發(fā)現(xiàn)其主要做了兩件事情,第一件事就是把 Connnctor(我們稱之為連接器)對(duì)象添加到 Tomcat 中,第二件事就是 configureEngine,這連接器我們勉強(qiáng)能理解(不理解后面會(huì)述說),那這個(gè) Engine 是什么呢?我們查看 tomcat.getEngine()的源碼:
public Engine getEngine() {
Service service = getServer().findServices()[0];if (service.getContainer() != null) {return service.getContainer();
}
Engine engine = new StandardEngine();
engine.setName( "Tomcat" );
engine.setDefaultHost(hostname);
engine.setRealm(createDefaultRealm());
service.setContainer(engine);return engine;
}
根據(jù)上面的源碼,我們發(fā)現(xiàn),原來這個(gè) Engine 是容器,我們繼續(xù)跟蹤源碼,找到 Container 接口
上圖中,我們看到了 4 個(gè)子接口,分別是 Engine,Host,Context,Wrapper。我們從繼承關(guān)系上可以知道他們都是容器,那么他們到底有啥區(qū)別呢?我看看他們的注釋是怎么說的。
/**
If used, an Engine is always the top level Container in a Catalina
* hierarchy. Therefore, the implementation's setParent() method
* should throw IllegalArgumentException.
*
* @author Craig R. McClanahan
*/public interface Engine extends Container {//省略代碼
}/**
*
* The parent Container attached to a Host is generally an Engine, but may
* be some other implementation, or may be omitted if it is not necessary.
*
* The child containers attached to a Host are generally implementations
* of Context (representing an individual servlet context).
*
* @author Craig R. McClanahan
*/
}/***
* The parent Container attached to a Context is generally a Host, but may
* be some other implementation, or may be omitted if it is not necessary.
*
* The child containers attached to a Context are generally implementations
* of Wrapper (representing individual servlet definitions).
*
*
* @author Craig R. McClanahan
*/public interface Context extends Container, ContextBind {//省略代碼
}/**
* The parent Container attached to a Wrapper will generally be an
* implementation of Context, representing the servlet context (and
* therefore the web application) within which this servlet executes.
*
* Child Containers are not allowed on Wrapper implementations, so the
* addChild() method should throw an
* IllegalArgumentException.
*
* @author Craig R. McClanahan
*/public interface Wrapper extends Container {//省略代碼
}
上面的注釋翻譯過來就是,Engine 是最高級(jí)別的容器,其子容器是 Host,Host 的子容器是 Context,Wrapper 是 Context 的子容器,所以這 4 個(gè)容器的關(guān)系就是父子關(guān)系,也就是 Engine>Host>Context>Wrapper。我們再看看 Tomcat 類的源碼:
//部分源碼,其余部分省略。public class Tomcat {//設(shè)置連接器public void setConnector(Connector connector) {
Service service = getService();boolean found = false;for (Connector serviceConnector : service.findConnectors()) {if (connector == serviceConnector) {
found = true;
}
}if (!found) {
service.addConnector(connector);
}
}//獲取servicepublic Service getService() {return getServer().findServices()[0];
}//設(shè)置Host容器public void setHost(Host host) {
Engine engine = getEngine();boolean found = false;for (Container engineHost : engine.findChildren()) {if (engineHost == host) {
found = true;
}
}if (!found) {
engine.addChild(host);
}
}//獲取Engine容器public Engine getEngine() {
Service service = getServer().findServices()[0];if (service.getContainer() != null) {return service.getContainer();
}
Engine engine = new StandardEngine();
engine.setName( "Tomcat" );
engine.setDefaultHost(hostname);
engine.setRealm(createDefaultRealm());
service.setContainer(engine);return engine;
}//獲取serverpublic Server getServer() {if (server != null) {return server;
}
System.setProperty("catalina.useNaming", "false");
server = new StandardServer();
initBaseDir();// Set configuration source
ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(new File(basedir), null));
server.setPort( -1 );
Service service = new StandardService();
service.setName("Tomcat");
server.addService(service);return server;
}//添加Context容器public Context addContext(Host host, String contextPath, String contextName,
String dir) {
silence(host, contextName);
Context ctx = createContext(host, contextPath);
ctx.setName(contextName);
ctx.setPath(contextPath);
ctx.setDocBase(dir);
ctx.addLifecycleListener(new FixContextListener());if (host == null) {
getHost().addChild(ctx);
} else {
host.addChild(ctx);
}//添加Wrapper容器public static Wrapper addServlet(Context ctx,
String servletName,
Servlet servlet) {// will do class for name and set init params
Wrapper sw = new ExistingStandardWrapper(servlet);
sw.setName(servletName);
ctx.addChild(sw);return sw;
}
}
閱讀 Tomcat 的 getServer()我們可以知道,Tomcat 的最頂層是 Server,Server 就是 Tomcat 的實(shí)例,一個(gè) Tomcat 一個(gè) Server;通過 getEngine()我們可以了解到 Server 下面是 Service,而且是多個(gè),一個(gè) Service 代表我們部署的一個(gè)應(yīng)用,而且我們還可以知道,Engine 容器,一個(gè) service 只有一個(gè);
根據(jù)父子關(guān)系,我們看 setHost()源碼可以知道,host 容器有多個(gè);同理,我們發(fā)現(xiàn) addContext()源碼下,Context 也是多個(gè);addServlet()表明 Wrapper 容器也是多個(gè),而且這段代碼也暗示了,其實(shí) Wrapper 和 Servlet 是一層意思。另外我們根據(jù) setConnector 源碼可以知道,連接器(Connector)是設(shè)置在 service 下的,而且是可以設(shè)置多個(gè)連接器(Connector)。
根據(jù)上面分析,我們可以小結(jié)下:Tomcat 主要包含了 2 個(gè)核心組件,連接器(Connector)和容器(Container),用圖表示如下:
一個(gè) Tomcat 是一個(gè) Server,一個(gè) Server 下有多個(gè) service,也就是我們部署的多個(gè)應(yīng)用,一個(gè)應(yīng)用下有多個(gè)連接器(Connector)和一個(gè)容器(Container),容器下有多個(gè)子容器,關(guān)系用圖表示如下:
Engine 下有多個(gè) Host 子容器,Host 下有多個(gè) Context 子容器,Context 下有多個(gè) Wrapper 子容器。
總結(jié)
SpringBoot 的啟動(dòng)是通過 new SpringApplication()實(shí)例來啟動(dòng)的,啟動(dòng)過程主要做如下幾件事情:> 1. 配置屬性 > 2. 獲取監(jiān)聽器,發(fā)布應(yīng)用開始啟動(dòng)事件 > 3. 初始化輸入?yún)?shù) > 4. 配置環(huán)境,輸出 banner > 5. 創(chuàng)建上下文 > 6. 預(yù)處理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 發(fā)布應(yīng)用已經(jīng)啟動(dòng)事件 > 10. 發(fā)布應(yīng)用啟動(dòng)完成事件
而啟動(dòng) Tomcat 就是在第 7 步中“刷新上下文”;Tomcat 的啟動(dòng)主要是初始化 2 個(gè)核心組件,連接器(Connector)和容器(Container),一個(gè) Tomcat 實(shí)例就是一個(gè) Server,一個(gè) Server 包含多個(gè) Service,也就是多個(gè)應(yīng)用程序,每個(gè) Service 包含多個(gè)連接器(Connetor)和一個(gè)容器(Container),而容器下又有多個(gè)子容器,按照父子關(guān)系分別為:Engine,Host,Context,Wrapper,其中除了 Engine 外,其余的容器都是可以有多個(gè)。
有道無術(shù),術(shù)可成;有術(shù)無道,止于術(shù)
歡迎大家關(guān)注Java之道公眾號(hào)
好文章,我在看??
總結(jié)
以上是生活随笔為你收集整理的class没有发布到tomcat_面试官扎心一问:Tomcat 在 SpringBoot 中是如何启动的?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么下拉框拉不下来_太气人了!《除暴》
- 下一篇: python定义类_提升你的Python