专栏电商日志财经减肥爱情
投稿投诉
爱情常识
搭配分娩
减肥两性
孕期塑形
财经教案
论文美文
日志体育
养生学堂
电商科学
头戴业界
专栏星座
用品音乐

源码探秘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 本文版权归作者所有

就喜欢玩刷装备的单机游戏,除了泰坦之旅有没有什么推荐?要说刷装备的游戏必然离不开始祖级的暗黑破坏神了。暗黑三也出了好几年了,前些日子出了死灵包可以玩死灵法师了。这游戏在刷刷刷类型游戏里的地位不用我多说了。恐怖黎明这也是款非常不错的作品LOL上路什么英雄好打剑魔,感觉跟剑魔对不了线,目前段位黄金?英雄联盟中,剑魔是重做得最成功的英雄之一,不管是线上,还是团战中都非常强势,但是又不是强得无脑。剑魔续航能力强,伤害也高,前期线上打短腿英雄,或者太脆的英雄,都是非常简单的。那么,LOL测试新英雄新皮肤,以及特效到时候,为什么挨打的永远是卡特?哈喽,大家好,我是你们的饭团君。英雄联盟之2011年推出至今已有8年,在这8年里,英雄联盟慢慢成为了全世界最火的网络游戏,从最开始的十几个英雄到现在的100多位英雄,英雄联盟前进的DNF95版本最新职业排名,ampquot纯C三耻ampquot变ampquot四耻ampquot,红眼初入下水道,你怎么看?最近95版本也是刚到国服,所以各方面的排名也是层出不穷,不过根据我这几天的观察,可以得出一个比较可观的事实,那就是不管任何排名,基本上红狗都是排在末尾的还是从幻神开始吧,铁打不动的你充值最多的一款游戏是什么?氪金最多的游戏现在很多游戏被玩家称之为坑,原因自然是氪金量实在太大了。出色的游戏设计师们,总是会有无数种办法让玩家在游戏过程中一而再再而三的管不住手,刚发完断手誓言,马上就又慷慨解作为曾经三相家族的一员,卢锡安为什么抛弃了这个完美级的装备?大约在S3时期卢锡安的出装尚是以三项为核心,配合轻语破败等其他攻速装备立马就成了峡谷中期最为顶尖的AD战力,我也不骗各位,在那个时期卢锡安绝对是下路AD霸主之一,超远距离的Q技能在LOL当劫R凯隐,凯隐R慎,慎R走,会出现什么效果?LOL当劫R凯隐,凯隐R慎,慎R走,会出现什么效果?英雄联盟召唤师们借助英雄的技能特性实现了许多不可思议的操作,例如阿卡丽的E挂印在正在传送的单位上可一并跟随到传送点,全图跑酷炫到王者荣耀钟无艳有输出同时也具有控制,但是在高端局和KPL中少见,原因在哪里?说起万金油型边路英雄,夏侯惇肯定是首当其冲的。这个英雄有盾有控,有位移,能回血,还有真实伤害,大招的CD还非常的短,完全可以说是一个完美的坦克边路英雄。夏侯惇使用的好,完全可以和凯绝地求生中,大神一般都用什么狙击枪?关注电竞小事,享受一手游戏咨询!绝地求生是一款非常热门的FPS枪战游戏,无论是普通玩家还是大神玩家都能够在游戏中找到各自的乐趣!那么对于大神而言,一般都用什么狙击枪呢?要知道,目前街机游戏里有哪些游戏里面有美女boss?俗话说,女为悦己者容,为了吸引玩家,游戏里涌现了一大批美女,街机游戏当然也不例外,下面GoGo就带你一起看看那些美颜动人的boss们先是Firstblood怒之铁拳最经典的女性BO经典游戏仙剑奇侠传哪些属性提高,可以增加李逍遥的技能伤害?在仙剑奇侠传最初的版本中,李逍遥能够学会的攻击技能比较少,分别是御剑术天师符法万剑诀天剑和剑神。除了酒神咒之外,其他技能都是当年在十里坡酒剑仙传授之后,慢慢领悟到的。在后期的每个阶
冰雪合击手游传奇萌新福利,合击技能免费领今日介绍的是冰雪合击这款手游传奇,这款手游传奇现已正式上线启动有一阵子了,也是有很多小伙伴去感受了这个游戏,反响基本也是不错的。这个手游传奇增多了角色游戏的玩法和合击技游戏的玩法,占领战略要地,Steam海盗游戏ATLAS玩家打造出易守难攻基地无论是在什么类型的沙盒游戏中,建筑玩法都是必不可少,ATLAS并不例外。这款Steam上的生存沙盒游戏引入了丰富的建筑元素,基于游戏极高的自由度,玩家可以自行选择搭配各种建筑单位,热血传奇我本沉默传奇手游幽灵船蚂蚁洞装备爆率新配方自古深情留不住,总是套路得人心,在这个没开美颜就不敢出门的时代,踏踏实实打磨游戏质量,敢于向所有玩家提供先试玩后付费服务的游戏,先让玩家一口气体验我本沉默的头顶战神帝,手握幽灵魔,战士榜大换血,铠皇马超沦为T3,能压制一切战士的她成功登顶T0哈喽,大家好!我是老张。众所周知,在王者荣耀当中,战士一直以来都是一个非常重要的构成体。通常这一类英雄都以边路位置出场,许多玩家认为,他们在前期往往都有着攻防兼备的特点,即便没有过五个守约也只能打出1点伤害!新装备超模?其实一个动作就能应对有的人虽然削了但他依然强势有的人虽然还没削但也马上就要躺枪了让我们来看看到底谁是倒霉蛋吧新版冰甲大解析新版冰甲五秒不受伤害获得减伤被动,让下一次伤害变成1点。这纯粹是是为了针对PO无差别鸣人技能受肯定,有鸣子出场,玩家直呼比忍战天天好太多可能很多玩家根据去年白面具的首波爆料时间,猜测这两天可能会有秽土鼬的首次爆料,但没想到却等来了无差别限定鸣人的全技能爆料。那我们就来提前分析一下这个忍者的情况吧,至少我个人感觉整体寂然暗黑骑士归来?貂蝉诸葛亮打野冲顶,法师真让他玩明白了估计很多玩家都喜欢玩什么冷门英雄或者用某些英雄去打一些不是很常见的位置。之前最早的时候就有玩家用亚瑟去打野,刚开始很多玩家都认为这种套路都是在乱玩,但是随着时间的退役亚瑟打野也受到天龙顶级欧皇连出两件极品九星装备,网友装备很好,下次别做了说起九星装备,相信老玩家们已经不陌生这并不是说,九星装备人手一件,主要是大家就算没出过,也见过别人出过吧?一般来说,有一件九星装备,那就是欧皇级人品,那连出两个呢?两件还都特别极品MVP加星卡上线,赛年皮肤官宣,白毛宫本巨帅,千色回城公布爱生活,爱游戏,大家好,我是阿呆。期待大家的关注,我会在这里分享更多有趣的最新资讯。前言随着王者荣耀体验服更新之后,有几个官方没有直接公布的消息已经正式透露,首先就是晒赛年皮肤得到KPL新限定爆料,匿光小队来袭,皮肤人选锁定镜,472点券别乱花前言随着KPL秋季赛的赛程进入尾声,全新的KPL皮肤也提上了日程,其中伽罗的天狼溯光者上线后,守护城市的天狼系列告辞一段落,不过从此前背景故事的彩蛋中,又发现并与本次爆料的内容呼应养剑大师攻略养剑大师是一款惊险刺激的动作冒险游戏,游戏有着非常简单的画风,趣味性极强,而且不需要联网就能进行游戏,你可以随时随地加入到探险中。游戏还有多种关卡及不同难度的挑战模式,每一次完成关
友情链接:快好知快生活快百科快传网中准网文好找聚热点快软件