范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

源码探秘Tomcat在SpringBoot中是如何启动的?

  前言[1]  从 Main 方法说起[2]  走进 Tomcat 内部[3]  总结[4]  前言
  我们知道 SpringBoot 给我们带来了一个全新的开发体验,我们可以直接把 web 程序达成 jar 包,直接启动,这就得益于 SpringBoot 内置了容器,可以直接启动,本文将以 Tomcat 为例,来看看 SpringBoot 是如何启动 Tomcat 的,同时也将展开学习下 Tomcat 的源码,了解 Tomcat 的设计。  从 Main 方法说起
  用过 SpringBoot 的人都知道,首先要写一个 main 方法来启动  @SpringBootApplication publicclass TomcatdebugApplication {      public static void main(String[] args) {         SpringApplication.run(TomcatdebugApplication.class, args);     }  }
  我们直接点击 run 方法的源码,跟踪下来,发下最终的 run 方法是调用 ConfigurableApplicationContext 方法,源码如下:  public ConfigurableApplicationContext run(String... args) {     StopWatch stopWatch = new StopWatch();     stopWatch.start();     ConfigurableApplicationContext context = null;     CollectionexceptionReporters = new ArrayList<>();     //设置系统属性『java.awt.headless』,为true则启用headless模式支持     configureHeadlessProperty();     //通过*SpringFactoriesLoader*检索*META-INF/spring.factories*,        //找到声明的所有SpringApplicationRunListener的实现类并将其实例化,        //之后逐个调用其started()方法,广播SpringBoot要开始执行了     SpringApplicationRunListeners listeners = getRunListeners(args);     //发布应用开始启动事件     listeners.starting();     try {     //初始化参数       ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);       //创建并配置当前SpringBoot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile),         //并遍历调用所有的SpringApplicationRunListener的environmentPrepared()方法,广播Environment准备完毕。       ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);       configureIgnoreBeanInfo(environment);       //打印banner       Banner printedBanner = printBanner(environment);       //创建应用上下文       context = createApplicationContext();       //通过*SpringFactoriesLoader*检索*META-INF/spring.factories*,获取并实例化异常分析器       exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,           new Class[] { ConfigurableApplicationContext.class }, context);       //为ApplicationContext加载environment,之后逐个执行ApplicationContextInitializer的initialize()方法来进一步封装ApplicationContext,         //并调用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一个空的contextPrepared()方法】,         //之后初始化IoC容器,并调用SpringApplicationRunListener的contextLoaded()方法,广播ApplicationContext的IoC加载完成,         //这里就包括通过**@EnableAutoConfiguration**导入的各种自动配置类。       prepareContext(context, environment, listeners, applicationArguments, printedBanner);       //刷新上下文       refreshContext(context);       //再一次刷新上下文,其实是空方法,可能是为了后续扩展。       afterRefresh(context, applicationArguments);       stopWatch.stop();       if (this.logStartupInfo) {         new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);       }       //发布应用已经启动的事件       listeners.started(context);       //遍历所有注册的ApplicationRunner和CommandLineRunner,并执行其run()方法。         //我们可以实现自己的ApplicationRunner或者CommandLineRunner,来对SpringBoot的启动过程进行扩展。       callRunners(context, applicationArguments);     }     catch (Throwable ex) {       handleRunFailure(context, ex, exceptionReporters, listeners);       throw new IllegalStateException(ex);     }      try {     //应用已经启动完成的监听事件       listeners.running(context);     }     catch (Throwable ex) {       handleRunFailure(context, ex, exceptionReporters, null);       throw new IllegalStateException(ex);     }     return context;   }
  其实这个方法我们可以简单的总结下步骤为 > 1. 配置属性 > 2. 获取监听器,发布应用开始启动事件 > 3. 初始化输入参数 > 4. 配置环境,输出 banner > 5. 创建上下文 > 6. 预处理上下文 > 7. 刷新上下文 > 8. 再刷新上下文 > 9. 发布应用已经启动事件 > 10. 发布应用启动完成事件
  其实上面这段代码,如果只要分析 tomcat 内容的话,只需要关注两个内容即可,上下文是如何创建的,上下文是如何刷新的,分别对应的方法就是 createApplicationContext() 和 refreshContext(context),接下来我们来看看这两个方法做了什么。  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) {         thrownew IllegalStateException(             "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass",             ex);       }     }     return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);   }
  这里就是根据我们的 webApplicationType 来判断创建哪种类型的 Servlet,代码中分别对应着 Web 类型(SERVLET),响应式 Web 类型(REACTIVE),非 Web 类型(default),我们建立的是 Web 类型,所以肯定实例化 DEFAULT_SERVLET_WEB_CONTEXT_CLASS 指定的类,也就是 AnnotationConfigServletWebServerApplicationContext 类
  我们来用图来说明下这个类的关系
  通过这个类图我们可以知道,这个类继承的是 ServletWebServerApplicationContext,这就是我们真正的主角,而这个类最终是继承了 AbstractApplicationContext,了解完创建上下文的情况后,我们再来看看刷新上下文,相关代码如下:  //类: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) {       thrownew 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());     }     elseif (servletContext != null) {       try {         getSelfInitializer().onStartup(servletContext);       }       catch (ServletException ex) {         thrownew ApplicationContextException("Cannot initialize servlet context", ex);       }     }     initPropertySources();   }
  到这里,其实庐山真面目已经出来了,createWebServer()就是启动 web 服务,但是还没有真正启动 Tomcat,既然 webServer 是通过 ServletWebServerFactory 来获取的,我们就来看看这个工厂的真面目。
  走进 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 接口
  上图中,我们看到了 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  */ publicinterface 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 inpidual 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 inpidual 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  */ publicinterface Wrapper extends Container {      //省略代码 }  上面的注释翻译过来就是,Engine 是最高级别的容器,其子容器是 Host,Host 的子容器是 Context,Wrapper 是 Context 的子容器,所以这 4 个容器的关系就是父子关系,也就是 Engine>Host>Context>Wrapper。  我们再看看 Tomcat 类的源码://部分源码,其余部分省略。 publicclass Tomcat { //设置连接器      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);         }     }     //获取service        public Service getService() {         return getServer().findServices()[0];     }     //设置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;     }     //获取server        public 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 的实例,一个 Tomcat 一个 Server  通过 getEngine()我们可以了解到 Server 下面是 Service,而且是多个,一个 Service 代表我们部署的一个应用,而且我们还可以知道,Engine 容器,一个 service 只有一个;根据父子关系,我们看 setHost()源码可以知道,host 容器有多个  同理,我们发现 addContext()源码下,Context 也是多个;addServlet()表明 Wrapper 容器也是多个,而且这段代码也暗示了,其实 Wrapper 和 Servlet 是一层意思。另外我们根据 setConnector 源码可以知道,连接器(Connector)是设置在 service 下的,而且是可以设置多个连接器(Connector)。根据上面分析,我们可以小结下:Tomcat 主要包含了 2 个核心组件,连接器(Connector)和容器(Container),用图表示如下:一个 Tomcat 是一个 Server,一个 Server 下有多个 service,也就是我们部署的多个应用,一个应用下有多个连接器(Connector)和一个容器(Container),容器下有多个子容器,关系用图表示如下:Engine 下有多个 Host 子容器,Host 下有多个 Context 子容器,Context 下有多个 Wrapper 子容器。总结SpringBoot 的启动是通过 new SpringApplication()实例来启动的,启动过程主要做如下几件事情:   1. 配置属性 2. 获取监听器,发布应用开始启动事件 3. 初始化输入参数 4. 配置环境,输出 banner 5. 创建上下文 6. 预处理上下文 7. 刷新上下文 8. 再刷新上下文 9. 发布应用已经启动事件 10. 发布应用启动完成事件而启动 Tomcat 就是在第 7 步中"刷新上下文";Tomcat 的启动主要是初始化 2 个核心组件,连接器(Connector)和容器(Container),一个 Tomcat 实例就是一个 Server,一个 Server 包含多个 Service,也就是多个应用程序,每个 Service 包含多个连接器(Connetor)和一个容器(Container),而容器下又有多个子容器,按照父子关系分别为:Engine,Host,Context,Wrapper,其中除了 Engine 外,其余的容器都是可以有多个。END 作者:木木匠来源:https://my.oschina.net/luozhou/blog/3088908 本文版权归作者所有

iPhone如何玩英雄联盟?教你快速注册下载日服东南亚服前段时间苹果发布会在线上召开,除了新机的发布,官方还向大家展示了用iPhone玩英雄联盟手游的画面。而英雄联盟手游的亮相,让许多玩家都想赶紧玩到游戏,但是许多用户并不知道如何方便快英雄联盟手游解压失败无法安装?日服东南亚服LOL手游安装指南前几天英雄联盟手游在在日韩和东南亚,安卓iOS双平台全面开放测试的消息,吸引了相当多玩家的注意,许多国内的玩家都通过加速器下载日服东南亚服LOL手游,进入全新的召唤师峡谷畅玩了。不哈利波特网易游戏为何如此淡定?宁愿业绩下滑也不牺牲手游品质哈利波特手游无论对于中国游戏圈还是网易游戏来说,肯定都是一款具有标志性的产品。不仅承载哈利波特粉丝23年来的热爱,更是拥有90后00后,乃至10后的游戏玩家们的深深期待。可自从8月为何专情香港明星代言?梁朝伟鸿图之下与邓紫棋万国觉醒不知道从何时开始,港台明星逐渐争夺下国内游戏的代言人的大盘。从林子聪陈小春张卫健郑伊健吴镇宇这批古惑仔开始,再到张家辉古天乐甄子丹的影帝级明星,甚至连TVB武侠剧的配角,各大游戏公VIVO怎么玩英雄联盟手游?快速注册下载日本东南亚LOL手游最近英雄联盟手游已经在日本和东南亚开放测试了,相信很多使用VIVO手机的玩家们,已经迫不及待想要进入游戏酣战一番,但许多人并不知道如何简单快捷的,在VIVO手机上注册和下载日服或东LOL手游东南亚服日服不会注册下载?三步教你在电脑玩英雄联盟近日,拳头官方宣布LOL手游即将迎来新一轮测试,此次测试最先开放注册的地区为日韩及东南亚,测试时间从太平洋时间10月27日起,并将在安卓IOS双平台共同开启,目前安卓日服已经开启偷黑潮之上如何免下载直接试玩?网易云游戏再送福利大礼包无限体力,逆转世界!黑潮之上公测开启,同步上线网易云游戏平台,更有游戏周边福利大派送!黑潮之上是一款拥有华丽的日系二次元立绘高质量3D表现精致的剧情MV,花泽香菜领衔献声,林友树打英雄联盟手游开放东南亚服日服注册,全网最便捷LOL外服下载相信许多小伙伴们已经从各种渠道,知晓了拳头即将开启新的LOL手游测试计划,此次测试将在安卓iOS双平台全面开放,从太平洋时间10月27日起,在日韩和东南亚地区进行测试,目前安卓日服英灵神殿valheim掉线卡顿延迟怎么办?网络问题方法汇总英灵神殿(valheim)是一款以维京文化为背景的开放世界生存游戏,不过很多玩家在与朋友一起联机合作探索游戏时,会出现掉线卡顿延迟等网络问题。小编有一招可以轻松解决这些问题,其实小重生细胞出现画面异常怎么办?用模拟器玩出现画面异常解决办法?重生细胞手游版近日上线,很多小伙伴会使用模拟器进行游戏。但使用模拟器有时会出现画面异常的问题。其实我们直接使用MuMu手游助手,即可解决该问题。下面就给大家分享一下如何用MuMu手原神1。2最低配置需求?网易云游戏无需配置即可流畅运行日前,原神官方宣布游戏1。2新版本白垩与黑龙,将于12月23日正式上线,即将开放的雪山区域,可以让玩家在游戏中也感受到冬季的凛冽之风,还有新的忍冬之树系统也将在这次更新后加入到游戏
Steam新游推荐1231索引琉隐(LiuyinORChingli)Clownfield2042风起长安驭骨人湖心亭奇談集(PeculiarTalesofMidLakePavilion)深渊公主(Relea吃鸡第4套圣装寒冰,3个印记领1个飞行器,光子真大方欢迎诸位小伙伴们来到天哥开讲的吃鸡小课堂许久没有和大家聊和平精英同根同源的PubgM(玩家俗称隔壁国际服),此前还在评论区里看到了催更,所以趁着和平精英最近忙着一系列返场连招时,前完美世界石昊的洞天中,都有哪些凶兽?来历更是无法预料石昊的洞天中,都有哪些凶兽?石昊在鲲鹏巢的中,也是晋级到了化灵境后期。而此时,石昊也在为自己的洞天养灵做准备。这样才能让自己以后的铭文镜晋级。而在洞天养灵中,灵兽的实力也会影响到他燃烧意志本次2。0的部分调整,还是不理想这一回合来说一下本次先锋2。0的部分调整,整体还是很迷,甚至没法称得上是优化。包括很多人关心的保底,自始至终都没有改。1通行证之前砍掉的奖励都补回来了,但是奖励的获取变得拖沓了。原云顶之弈s6最强前期灰色海克斯一hr当拥有这个海克斯之后,其实我们就可以把这个理解为f到上头。在正常爆装备6块钱的前提下,21升4,22或23升5,24升6。依靠每回合多给的2金币。在前期不需要存钱的情况下每回暴雪为暗黑破坏神2NS版举办直播活动梶田光头形象现身近日,暴雪为旗下的暗黑破坏神2举办了一场生放送的直播活动,介绍了登陆任天堂Switch的这款经典游戏的重制版本。同时为了炒热直播的气氛,请来了两位生放送大户梶田大光头和中村悠一,下斗地主大赛嘴硬真没用!水晶哥罕见破防,吕德华成最后赢家前言有虎牙举办的斗地主大赛KPIS2已经圆满结束了,最终吕德华也是艰难的拿下了冠军!本次斗地主大赛可以说是聚集了各大游戏的头部主播,其中最具有的当属王者荣耀以及英雄联盟,这些主播对幻塔巴巴罗萨怎么打怪物打法攻略在幻塔手游的地图中分布着许多大大小小的各种BOSS,巴巴罗萨就是其中比较难打的一个的,有不少小伙伴都不知道幻塔巴巴罗萨怎么打,下面小编就为大家带来了相关的打法攻略,就让我们一起来看LOL美服真的凉了?前SKT上单吐槽100多分钟排不到人,快窒息了前言众所周知,目前LOL职业联赛中,最强力的赛区只有两个,那就是我们LPL和韩国LCK,其余的LECLCS等外卡赛区,他们的战斗力都远远不如我们LPL和LCK,这也就使得该地区的玩热血传奇合击版有哪些合击技能迄今为止,早期的传奇已经发展到无数版本。可想而知,玛法三英的层次很难提升。记忆中的稻草人,比奇的多钩猫,承载了太多人的激情和青春回忆。一道裁决大摇大摆的划过市场,无数羡慕的目光。一地平线2西部禁域已公布的新机械怪兽信息汇总外媒Gameinformer汇总了地平线2目前已公布的其它新敌人供大家参考。卷背兽(Rollerback)这是一种类似巨型犰狳的敌人,它们也能像犰狳一样卷成一团发动滚球冲撞攻击。它