day03-分析SpringBoot底层机制

打印 上一主题 下一主题

主题 1028|帖子 1028|积分 3084

分析SpringBoot底层机制

Tomcat启动分析,Spring容器初始化,Tomcat如何关联Spring容器?
1.创建SpringBoot环境

(1)创建Maven程序,创建SpringBoot环境
(2)pom.xml导入SpringBoot的父工程和依赖
  1. <parent>
  2.     <artifactId>spring-boot-starter-parent</artifactId>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <version>2.5.3</version>
  5. </parent>
  6. <dependencies>
  7.    
  8.     <dependency>
  9.         <groupId>org.springframework.boot</groupId>
  10.         <artifactId>spring-boot-starter-web</artifactId>
  11.     </dependency>
  12. </dependencies>
复制代码
(3)创建主程序MainApp.java
  1. package com.li.springboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.ConfigurableApplicationContext;
  5. /**
  6. * @author 李
  7. * @version 1.0
  8. */
  9. @SpringBootApplication//表示SpringBoot项目
  10. public class MainApp {
  11.     public static void main(String[] args) {
  12.         //启动SpringBoot项目
  13.         ConfigurableApplicationContext ioc =
  14.                 SpringApplication.run(MainApp.class, args);
  15.     }
  16. }
复制代码
(4)启动项目,我们可以注意到Tomcat也随之启动了。
问题一:当我们执行run方法时,为什么会启动我们内置的tomcat?它的底层是如何实现的?
2.Spring容器初始化(@Configuration+@Bean)

我们知道,如果在一个类上添加了注解@Configuration,那么这个类就会变成配置类;配置类中通过@Bean注解,可以将方法中 new 出来的Bean对象注入到容器中,该bean对象的id默认为方法名。
配置类本身也会作为bean注入到容器中
容器初始化的底层机制仍然是我们之前分析的Spring容器的机制(IO/文件扫描+注解+反射+集合+映射)
对比:

  • Spring通过@ComponentScan,指定要扫描的包;而SpringBoot默认从主程序所在的包开始扫描,同时也可以指定要扫描的包(scanBasePackages = {"xxx.xx"})。
  • Spring通过xml或者注解,指定要注入的bean;SpringBoot通过扫描配置类(对应spring的xml)的@Bean或者注解,指定注入bean
3.SpringBoot怎样启动Tomcat,并能支持访问@Controller?

由前面的例子1中可以看到,当启动SpringBoot时,tomcat也会随之启动。那么问题来了:

  • SpringBoot是怎么内嵌Tomcat,并启动Tomcat的?
  • 而且底层是怎样让@Controller修饰的控制器也可以被访问的?
3.1源码分析SpringApplication.run()

SpringApplication.run()方法会完成两个重要任务:

  • 创建容器
  • 容器的刷新:包括参数的刷新+启动Tomcat
(1)创建一个控制器
  1. package com.li.springboot.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. /**
  5. * @author 李
  6. * @version 1.0
  7. * HiController被标注后,作为一个控制器注入容器中
  8. */
  9. @RestController//相当于@Controller+@ResponseBody
  10. public class HiController {
  11.     @RequestMapping("/hi")
  12.     public String hi() {
  13.         return "hi,HiController";
  14.     }
  15. }
复制代码
(2)启动主程序MainApp.java,进行debug
(3)首先进入SpringApplication.java的run方法
(4)点击step into,进入如下方法
  1. public ConfigurableApplicationContext run(String... args) {
  2.     ...
  3.     try {
  4.         ...
  5.         context = this.createApplicationContext();//严重分析,创建容器
  6.         context.setApplicationStartup(this.applicationStartup);
  7.         this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
  8.         this.refreshContext(context);//刷新应用上下文,比如初始化默认设置/注入相关bean/启动Tomcat
  9.         this.afterRefresh(context, applicationArguments);
  10.         stopWatch.stop();
  11.         ...
  12.     } catch (Throwable var10) {...}
  13.     ...
  14. }
复制代码
(5)分别对 **createApplicationContext() **和 refreshContext(context) 方法进行分析:
(5.1)step into 进入 **createApplicationContext() ** 方法中:
  1. //springApplication.java
  2. //容器类型很多,会根据你的this.webApplicationType创建对应的容器,默认this.webApplicationType
  3. //的类型为SERVLET,也就是web容器(可以处理servlet)
  4. protected ConfigurableApplicationContext createApplicationContext() {
  5.     return this.applicationContextFactory.create(this.webApplicationType);
  6. }
复制代码
(5.2)点击进入下一层
  1. //接口 ApplicationContextFactory.java
  2. //该方法根据webApplicationType创建不同的容器
  3. ApplicationContextFactory DEFAULT = (webApplicationType) -> {
  4.     try {
  5.         switch(webApplicationType) {
  6.         case SERVLET://默认进入这一分支,返回
  7.                 //AnnotationConfigServletWebServerApplicationContext容器
  8.             return new AnnotationConfigServletWebServerApplicationContext();
  9.         case REACTIVE:
  10.             return new AnnotationConfigReactiveWebServerApplicationContext();
  11.         default:
  12.             return new AnnotationConfigApplicationContext();
  13.         }
  14.     } catch (Exception var2) {
  15.         throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);
  16.     }
  17. };
复制代码
总结:createApplicationContext()方法中创建了容器,但是还没有将bean注入到容器中。
(5.3)step into 进入 refreshContext(context) 方法中:
  1. //springApplication.java
  2. private void refreshContext(ConfigurableApplicationContext context) {
  3.     if (this.registerShutdownHook) {
  4.         shutdownHook.registerApplicationContext(context);
  5.     }
  6.     this.refresh(context);//核心,真正执行相关任务
  7. }
复制代码
(5.4)在this.refresh(context);这一步进入下一层:
  1. //springApplication.java
  2. protected void refresh(ConfigurableApplicationContext applicationContext) {
  3.     applicationContext.refresh();
  4. }
复制代码
(5.5)继续进入下一层:
  1. protected void refresh(ConfigurableApplicationContext applicationContext) {
  2.     applicationContext.refresh();
  3. }
复制代码
(5.6)继续进入下一层:
  1. //ServletWebServerApplicationContext.java
  2. public final void refresh() throws BeansException, IllegalStateException {
  3.     try {
  4.         super.refresh();
  5.     } catch (RuntimeException var3) {
  6.         WebServer webServer = this.webServer;
  7.         if (webServer != null) {
  8.             webServer.stop();
  9.         }
  10.         throw var3;
  11.     }
  12. }
复制代码
(5.7)在super.refresh();这一步进入下一层:
  1. //AbstractApplicationContext.java
  2. @Override
  3. public void refresh() throws BeansException, IllegalStateException {
  4.    synchronized (this.startupShutdownMonitor) {
  5.       StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
  6.      ...
  7.       try {
  8.         ...
  9.          // Initialize other special beans in specific context subclasses.
  10.          //在上下文的子类初始化指定的bean
  11.          onRefresh(); //当父类完成通用的工作后,再重新用动态绑定机制回到子类
  12.         ...
  13.       }
  14.       catch (BeansException ex) {...}
  15.       finally {...}
  16.    }
  17. }
复制代码
(5.8)在onRefresh();这一步step into,会重新返回上一层:
  1. //ServletWebServerApplicationContext.java
  2. protected void onRefresh() {
  3.     super.onRefresh();
  4.     try {
  5.         this.createWebServer();//创建一个webserver,可以理解成创建我们指定的web服务-Tomcat
  6.     } catch (Throwable var2) {
  7.         throw new ApplicationContextException("Unable to start web server", var2);
  8.     }
  9. }
复制代码
(5.9)在this.createWebServer();这一步step into:
  1. //ServletWebServerApplicationContext.java
  2. private void createWebServer() {
  3.     WebServer webServer = this.webServer;
  4.     ServletContext servletContext = this.getServletContext();
  5.     if (webServer == null && servletContext == null) {
  6.         StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
  7.         ServletWebServerFactory factory = this.getWebServerFactory();
  8.         createWebServer.tag("factory", factory.getClass().toString());
  9.         this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});//使用TomcatServletWebServerFactory创建一个TomcatWebServer
  10.         createWebServer.end();
  11.         this.getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));
  12.         this.getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));
  13.     } else if (servletContext != null) {
  14.         try {
  15.             this.getSelfInitializer().onStartup(servletContext);
  16.         } catch (ServletException var5) {
  17.             throw new ApplicationContextException("Cannot initialize servlet context", var5);
  18.         }
  19.     }
  20.     this.initPropertySources();
  21. }
复制代码
(5.10)在this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});这一步step into:
  1. //TomcatServletWebServerFactory.java会创建Tomcat,并启动Tomcat
  2. public WebServer getWebServer(ServletContextInitializer... initializers) {
  3.     if (this.disableMBeanRegistry) {
  4.         Registry.disableRegistry();
  5.     }
  6.     Tomcat tomcat = new Tomcat();//创建了Tomcat对象,下面是一系列的初始化任务
  7.     File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
  8.     tomcat.setBaseDir(baseDir.getAbsolutePath());
  9.     Connector connector = new Connector(this.protocol);
  10.     connector.setThrowOnFailure(true);
  11.     tomcat.getService().addConnector(connector);
  12.     this.customizeConnector(connector);
  13.     tomcat.setConnector(connector);
  14.     tomcat.getHost().setAutoDeploy(false);
  15.     this.configureEngine(tomcat.getEngine());
  16.     Iterator var5 = this.additionalTomcatConnectors.iterator();
  17.     while(var5.hasNext()) {
  18.         Connector additionalConnector = (Connector)var5.next();
  19.         tomcat.getService().addConnector(additionalConnector);
  20.     }
  21.     this.prepareContext(tomcat.getHost(), initializers);
  22.     return this.getTomcatWebServer(tomcat);
  23. }
复制代码
(5.11)在return this.getTomcatWebServer(tomcat);这一步step into:
  1. //TomcatServletWebServerFactory.java
  2. //这里做了端口校验,创建了TomcatWebServer
  3. protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
  4.     return new TomcatWebServer(tomcat, this.getPort() >= 0, this.getShutdown());
  5. }
复制代码
(5.12)继续step into进入下一层
  1. //TomcatServletWebServerFactory.java
  2. public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {
  3.     this.monitor = new Object();
  4.     this.serviceConnectors = new HashMap();
  5.     Assert.notNull(tomcat, "Tomcat Server must not be null");
  6.     this.tomcat = tomcat;
  7.     this.autoStart = autoStart;
  8.     this.gracefulShutdown = shutdown == Shutdown.GRACEFUL ? new GracefulShutdown(tomcat) : null;
  9.     this.initialize();//进行初始化,并启动tomcat
  10. }
复制代码
(5.13)this.initialize();继续step into:
  1. //TomcatServletWebServerFactory.java
  2. private void initialize() throws WebServerException {
  3.     logger.info("Tomcat initialized with port(s): " + this.getPortsDescription(false));
  4.     synchronized(this.monitor) {
  5.         try {
  6.             this.addInstanceIdToEngineName();
  7.             Context context = this.findContext();
  8.             context.addLifecycleListener((event) -> {
  9.                 if (context.equals(event.getSource()) && "start".equals(event.getType())) {
  10.                     this.removeServiceConnectors();
  11.                 }
  12.             });
  13.             this.tomcat.start();//启动Tomcat!
  14.             this.rethrowDeferredStartupExceptions();
  15.             try {
  16.                 ContextBindings.bindClassLoader(context, context.getNamingToken(), this.getClass().getClassLoader());
  17.             } catch (NamingException var5) {
  18.             }
  19.             this.startDaemonAwaitThread();
  20.         } catch (Exception var6) {
  21.             this.stopSilently();
  22.             this.destroySilently();
  23.             throw new WebServerException("Unable to start embedded Tomcat", var6);
  24.         }
  25.     }
  26. }
复制代码
(6)一路返回上层,然后终于执行完refreshContext(context)方法,此时context为已经注入了bean

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

伤心客

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表