iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Tomcat中怎么启动SpringBoot
  • 481
分享到

Tomcat中怎么启动SpringBoot

2023-06-16 19:06:33 481人浏览 独家记忆
摘要

这篇文章给大家介绍Tomcat中怎么启动SpringBoot,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。从 Main 方法说起用过springBoot的人都知道,首先要写一个main方法来启动@SpringBootA

这篇文章给大家介绍Tomcat中怎么启动SpringBoot,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

从 Main 方法说起

用过springBoot的人都知道,首先要写一个main方法来启动

@SpringBootApplication  public class 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;          Collection<springbootexceptionreporter> exceptionReporters = new ArrayList&lt;&gt;();          //设置系统属性『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) {                  throw new 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类,我们来用图来说明下这个类的关系

Tomcat中怎么启动SpringBoot

通过这个类图我们可以知道,这个类继承的是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) {              throw new ApplicationContextException("Unable to start web server", ex);          }      }   private void createWebServer() {          WebServer webServer = this.webServer;          ServletContext servletContext = getServletContext();          if (webServer == null &amp;&amp; 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。我们从继承关系上可以知道他们都是容器,那么他们到底有啥区别呢?我看看他们的注释是怎么说的。

   public interface Engine extends Container {      //省略代码  }    public interface Host extends Container {  //省略代码   }    public interface Context extends Container, ContextBind {      //省略代码  }    public interface Wrapper extends Container {      //省略代码  }

上面的注释翻译过来就是,Engine是最高级别的容器,其子容器是Host,Host的子容器是Context,Wrapper是Context的子容器,所以这4个容器的关系就是父子关系,也就是Engine>Host>Context>Wrapper。 我们再看看Tomcat类的源码:

//部分源码,其余部分省略。  public class 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中怎么启动SpringBoot

一个Tomcat是一个Server,一个Server下有多个service,也就是我们部署的多个应用,一个应用下有多个连接器(Connector)和一个容器(Container),容器下有多个子容器,关系用图表示如下:

Tomcat中怎么启动SpringBoot

关于Tomcat中怎么启动SpringBoot就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

--结束END--

本文标题: Tomcat中怎么启动SpringBoot

本文链接: https://www.lsjlt.com/news/285010.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Tomcat中怎么启动SpringBoot
    这篇文章给大家介绍Tomcat中怎么启动SpringBoot,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。从 Main 方法说起用过SpringBoot的人都知道,首先要写一个main方法来启动@SpringBootA...
    99+
    2023-06-16
  • tomcat怎么启动springboot项目
    要启动Spring Boot项目,可以使用Tomcat来进行部署。以下是启动Spring Boot项目的步骤:1. 首先,确保你的S...
    99+
    2023-10-10
    tomcat springboot
  • 如何在SpringBoot中启动tomcat
    如何在SpringBoot中启动tomcat?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。springboot是什么springboot一种全新的编程规范,其设计目的是用来...
    99+
    2023-06-14
  • 怎么在Eclipse中启动Tomcat
    要在Eclipse中启动Tomcat,您需要遵循以下步骤:1. 确保您已经安装了Eclipse和Tomcat。如果还没有安装,请先下...
    99+
    2023-09-14
    Tomcat
  • Linux下怎么启动tomcat
    这篇文章主要介绍“Linux下怎么启动tomcat”,在日常操作中,相信很多人在Linux下怎么启动tomcat问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linux下怎么启动tomcat”的疑惑有所帮助!...
    99+
    2023-06-09
  • springboot启动报错Unable to start embedded Tomcat
    这个错误通常是由于端口冲突或者Tomcat配置错误导致的。以下是一些可能的解决方案:1. 检查端口是否被占用:可以使用以下命令查看系...
    99+
    2023-09-08
    springboot
  • Tomcat中SpringBoot应用无法启动如何解决
    Tomcat中SpringBoot应用无法启动如何解决?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。问题描述我修改pom.xml将打包方式改成war<packagin...
    99+
    2023-05-31
    springboot omc tomcat
  • SpringBoot Tomcat启动实例代码详解
    废话不多了,具体内容如下所示:Application configuration class:@SpringBootApplicationpublic class ServletInitializer extends SpringBootS...
    99+
    2023-05-31
    spring boot tomcat
  • springboot使用外置tomcat启动方式
    目录使用外置tomcat启动使用外置的tomcat启动注意事项 使用外置tomcat启动 打开pom文件,把打包格式设置为war <packaging>war<...
    99+
    2024-04-02
  • SpringBoot内置tomcat启动原理详解
    前言 不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在spring...
    99+
    2024-04-02
  • 传统tomcat启动服务与springboot启动内置tomcat服务的区别(推荐)
    spring整合springmvc  spring整合springmvc中web.xml配置如下,tomcat在启动过程中会加载web.xml中的内容,Conte...
    99+
    2024-04-02
  • tomcat中startup启动不了怎么解决
    如果Tomcat中的startup无法启动,可能是由于以下原因之一: 端口被占用:请确保Tomcat所使用的端口没有被其他应用程...
    99+
    2023-10-22
    tomcat startup
  • springboot中如何利用Tomcat容器实现自启动
    这篇“springboot中如何利用Tomcat容器实现自启动”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“springbo...
    99+
    2023-06-08
  • SpringBoot启动嵌入式Tomcat的实现步骤
    目录Spring Boot中Web容器相关接口WebServerServletWebServerFactoryWebServerFactoryCustomizerBeanPostPr...
    99+
    2024-04-02
  • SpringBoot启动嵌入式Tomcat的实现过程
    本篇内容介绍了“SpringBoot启动嵌入式Tomcat的实现过程”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!目录Spring Boot...
    99+
    2023-06-20
  • tomcat启动卡住不动怎么解决
    当Tomcat启动卡住不动时,可能是由于以下原因造成的:1. 端口冲突:检查其他应用程序是否正在使用Tomcat所需的端口号。如果是...
    99+
    2023-08-30
    tomcat
  • linux怎么设置tomcat自启动
    这篇“linux怎么设置tomcat自启动”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“l...
    99+
    2024-04-02
  • tomcat怎么启动两个war包
    要在Tomcat中启动两个WAR包,可以按照以下步骤操作: 将两个WAR包分别放置在Tomcat的webapps目录下,确保每个...
    99+
    2024-03-04
    tomcat
  • tomcat启动内存怎么设置
    Tomcat启动内存可以通过设置JAVA_OPTS环境变量来进行配置。具体步骤如下: 打开Tomcat的启动脚本,一般在bin目录...
    99+
    2024-03-13
    tomcat
  • tomcat怎么设置jvm启动参数
    要设置Tomcat的JVM启动参数,可以按照以下步骤进行操作: 打开Tomcat的配置文件catalina.sh(Linux/U...
    99+
    2023-10-23
    tomcat jvm
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作