Springboot 原理

时间:2022-07-23
本文章向大家介绍Springboot 原理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Springboot 帮助快速搭建java 应用程序,包括web和console 应用程序。 默认继承一般需要的依赖。 例如web应用会继承:tomcat-servlet, Jackson,oauth2,WebMvc等等。

Springboot项目有10个模块

  1. spring-boot

四大功能:

  • SpringApplication,功能就是保证创建和刷新ApplicationContext
  • 嵌入的web程序,可选择Tomcat, Jetty or Undertow
  • 外部配置支持
  • ApplicationContext初始化
  • spring-boot-autoconfigure,

通过@EnableAutoConfiguration 启用,检测用户可能需要的bean。 例如, 如果HSQLDB在classpath里面, 并且用户没有设置数据库链接, 很可能需要一个内存数据库,springBoot会重新指派一个

这里设置了大量的默认类,约定优于配置主要体现在这里

  1. spring-boot-starter

依赖集合。 spring 一站式依赖集合, 如spring-boot-starter-web,等。 在pom.xm 指定即可

  1. spring-boot-cli

命令行工具,用来编译和执行Groovy代码

  1. spring-boot-atuator

程序监测, 使用它可以通过http,或者jmx 来审计,健康监测,以及指标收集。

  1. spring-boot-actuator-autoconfigure

自动配置自动监测

  1. spring-boot-test

自动化测试

  1. spring-boot-test-autoconfigure

自动化测试自动配置

  1. spring-boot-loader

用来构建 single jar, 这样的jar 可以用java -jar 来启动。 一般不直接使用,而是通过maven 插件来达到同样的功能

  1. spring-boot-devtools

Springboot 启动过程

  1. 载入。

SpringApplication 构造

  1. 设置resourceLoder. 默认是annotation loader
  2. 载入全部主要资源(primarySources)
  3. 设置webApplicationType. 从classpath推导
  4. 收集初始化器(ApplicationContextInitializer, 继承这个接口的类)
  5. 收集Listener. (ApplicationListener, 继承这个接口的类)
  6. 推导main class.

这个推导方法有点意思:

private Class<?> deduceMainApplicationClass() {
 try {
      				StackTraceElement[] stackTrace = 
new RuntimeException().getStackTrace();
 for (StackTraceElement stackTraceElement : stackTrace) {
 if ("main".equals(stackTraceElement.getMethodName())) {
 return 	
Class.forName(stackTraceElement.getClassName());
        				 }
      				}
   				}
 catch (ClassNotFoundException ex) {
 // Swallow and continue
 }
 return null;
}
  1. 启动运行(run)。 属于sprint-boot 模块
  2. 设置环境 prepareEnvironment

根据不同的context (servlet, reactiveWeb or standard)设置环境变量,

默认环境变量:

systemEnvironment

systemProperties

servletContextInitParams

servletConfigInitParams

jndiProperties

servlet

reactive web

standard

  1. 创建ConfigurableApplicationContext,

有三种ConfigurableApplicationContext:

  1. 默认 传统Servlet web AnnotationConfigServletWebServerApplicationContext
  2. 非阻塞reactive web AnnotationConfigReactiveWebServerApplicationContext
  3. 非web应用程序 AnnotationConfigServletWebServerApplicationContext

非Web应用就是普通的consol程序。 关于 Servlet web 和 Reactive web 见另我一篇文章 spring boot中的web技术

  1. 根据context 准备 beanContext,方法 prepareContext,
  2. 设置context 环境变量,

环境变量包括 Profile, 系统环境变量,系统属性(SystemProperties)

设置beanDefinitionReader(xmlReader,annotationReader,groovyReader) 和

classpath beandefinition scanner, 以决定是通过xml 定义还是注解定义的bean.

  1. 注册单例的bean。
  2. 设置资源加载器
  3. 设置classLoader
  4. 设置转换服务,如 stringToDuration, durationToString等
  5. 应用初始化器
  6. 载入资源(创建beans)
  7. refreshContext。 web server 是在这一步创建的。

程序都继承 AbstractApplicationContext,包括web程序

  1. afterRefresh
  2. 执行main函数

Springboot启动例子

  1. jvm classLoader 加载类
  2. 启动springboot 启动流程