Tomcat 在 SpringBoot 中是如何启动的?,Java小程序开发实例

//类:SpringApplication.java

private void refreshContext(ConfigurableApplicationContext context) {

//直接调用刷新方法

refresh(context);

if (this.registerShutdownHook) {

try {

context.registerShutdownHook();

}

catch (AccessControlException ex) {

// Not allowed in some environments.

}

}

}

//类:SpringApplication.java

protected void refresh(ApplicationContext applicationContext) {

Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);

((AbstractApplicationContext) applicationContext).refresh();

}

这里还是直接传递调用本类的 refresh(context)方法,最后是强转成父类

AbstractApplicationContext 调用其 refresh()方法,该代码如下:

// 类:AbstractApplicationContext

public 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.这里的意思就是调用各个子类的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()方法是调用其子类的实现,根据我们上文的分析,我们这里的子类是

ServletWebServerApplicationContext。

//类:ServletWebServerApplicationContext

protected 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();

}

到这里,其实庐山真面目已经出来了,createWebServer()就是启动 web 服务,但是还没有真正启动 Tomcat,既然 webServer 是通过 ServletWebServerFactory 来获取的,我们就来看看这个工厂的真面目。

面试官扎心一问:Tomcat 在 SpringBoot 中是如何启动的?

走进 Tomcat 内部

================

根据上图我们发现,工厂类是一个接口,各个具体服务的实现是由各个子类来实现的,所以我们就去看看

TomcatServletWebServerFactory.getWebServer()的实现。

@Override

public 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);

}

根据上面的代码,我们发现其主要做了两件事情,第一件事就是把 Connnctor(我们称之为连接器)对象添加到 Tomcat 中,第二件事就是 configureEngine,这连接器我们勉强能理解(不理解后面会述说),那这个 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;

}

根据上面的源码,我们发现,原来这个 Engine 是容器,我们继续跟踪源码,找到 Container 接口

面试官扎心一问:Tomcat 在 SpringBoot 中是如何启动的?

上图中,我们看到了 4 个子接口,分别是 Engine,Host,Context,Wrapper。我们从继承关系上可以知道他们都是容器,那么他们到底有啥区别呢?我看看他们的注释是怎么说的。

/**

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

*/

public interface Host extends Container {

//省略代码

}

/***

  • 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 是最高级别的容器,其子容器是 Host,Host 的子容器是 Context,Wrapper 是 Context 的子容器,所以这 4 个容器的关系就是父子关系,也就是 Engine>Host>Context>Wrapper。我们再看看 Tomcat 类的源码:

//部分源码,其余部分省略。

public class Tomcat {

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
img

最后

整理的这些资料希望对Java开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

image

image

其实面试这一块早在第一个说的25大面试专题就全都有的。以上提及的这些全部的面试+学习的各种笔记资料,我这差不多来回搞了三个多月,收集整理真的很不容易,其中还有很多自己的一些知识总结。正是因为很麻烦,所以对以上这些学习复习资料感兴趣,

awTE3OEh-1711159294730)]
[外链图片转存中…(img-h2acvup8-1711159294731)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
[外链图片转存中…(img-X5jNnRtN-1711159294731)]

最后

整理的这些资料希望对Java开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

[外链图片转存中…(img-t395Ibwg-1711159294732)]

[外链图片转存中…(img-ZGQsEujm-1711159294733)]

其实面试这一块早在第一个说的25大面试专题就全都有的。以上提及的这些全部的面试+学习的各种笔记资料,我这差不多来回搞了三个多月,收集整理真的很不容易,其中还有很多自己的一些知识总结。正是因为很麻烦,所以对以上这些学习复习资料感兴趣,

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值