博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot启动流程及其原理
阅读量:3967 次
发布时间:2019-05-24

本文共 9122 字,大约阅读时间需要 30 分钟。

springboot学习笔记:附上教学视频:https://www.bilibili.com/video/BV1PE411i7CV?spm_id_from=pageDriver

1、回顾spring

1.1 spring介绍

spring是一个开源的框架, 作者:Rod Johsonspring是为了解决企业级应用开发的复杂性而创建的,简化开发。

1.2 spring如何简化java开发的

1、基于POJO的轻量级和最小侵入性编程,所有东西都是bean;2、通过IOC,依赖注入(DI)和面向接口实现松耦合;3、基于切面(AOP)和惯例进行声明式编程;4、通过切面和模版减少样式代码,RedisTemplate,xxxTemplate;

2、什么是springboot

2.1springboot

约定大于配置

2.2springboot的优点

简化spring的开发开箱即用,提供各种默认配置简化项目的配置内嵌式容器简化web开发没有冗余代码和先买来的配置接口

3、springboot 快速入门

3.1 创建方式一

​ 1.打开

​ 2.填写信息,生成项目,配置maven,在IDEA导入maven项目。等待即可

3.2创建方式二

​ 1.使用Idea 创建一个新的项目

​ 2.选择spring initalizr,填写信息,选择初始化组件(web)、路径等待项目构建成功。

4、运行原理

4.1 父依赖

springboot 的pom.xml中主要依赖一个父项目,主要是管理项目里面的资源过滤以及插件!

org.springframework.boot
spring-boot-starter-parent
2.4.5

按住Ctrl点击2.4.5进入里面有一个父依赖,里面有许多约束,自行阅读.

org.springframework.boot
spring-boot-dependencies
2.4.5

用 框架除了开发少数的独立应用,大部分情况下实际上在使用 SpringMVC 开发 web 应用,为了帮我们简化快速搭建并开发一个 Web 项目, 为我们提供了 spring-boot-starter-web 自动配置模块。

spring-boot-starter-web 默认将为我们自动配置如下一些 SpringMVC 必要组件:

  • 必要的 ViewResolver,比如 ContentNegotiatingViewResolver 和 Bean-NameViewResolver。
  • 将必要的 Converter、GenericConverter 和 Formatter 等 bean 注册到 IoC 容器。
  • 添加一系列的 HttpMessageConverter 以便支持对 Web 请求和相应的类型转换。
  • 自动配置和注册 MessageCodesResolver。
  • 其他。
org.springframework.boot
spring-boot-starter-web
---->重要的描述:
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
---->里面配置了JSON、tomcat、spring-web、spring-webmvc相关的jar包

4.2主启动类

4.2.1默认的主启动类

//@SpringBootApplication 来标注一个主程序类@SpringBootApplicationpublic class SpringbootApplication {
public static void main(String[] args) {
//以为是启动了一个方法,没想到启动了一个服务 SpringApplication.run(SpringbootApplication.class, args); }}

4.2.2@SpringBootApplication

作用:标注在某个类上面说明了这个类就是springboot的主配置类,springboot运行了这个类的main方法启动某个springboot应用。
这个类注解里面有好多注解@Target({
ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan( excludeFilters = {
@Filter( type = FilterType.CUSTOM, classes = {
TypeExcludeFilter.class}), @Filter( type = FilterType.CUSTOM, classes = {
AutoConfigurationExcludeFilter.class})})public @interface SpringBootApplication {
.....}

4.2.3 @ComponextScan

作用:自动扫描并加载符合条件的组件或者bean,把bean交给IOC容器管理和spring的配置文件xml文件对应

4.2.4 @SpringBootConfiguration

作用:标注在某一个类上面,表示springboot的配置类。
@Target({
ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Configuration //说明了这是一个配置类,对应spring的xml配置文件public @interface SpringBootConfiguration {
@AliasFor( annotation = Configuration.class ) boolean proxyBeanMethods() default true;}

@EnableAutoConfiguration

这个注解表示可以自动帮我们配置,开启自动配置才能生效,告诉springboot开启自动配置,这样就能够生效。
@Target({
ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import({
AutoConfigurationImportSelector.class})public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class
[] exclude() default {
}; String[] excludeName() default {
};}

@AutoConfigurationPackage

这个注解表示是:自动配置包
@Target({
ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Import({
Registrar.class})public @interface AutoConfigurationPackage {
}

@import

Spring底层注解@import,表示给容器导入一个组件Registrar.class的作用:将主启动类的所有包以及自包里面的所有组件扫描到spring容器里面

退回上一步继续看源码

4.2.5 @Import({AutoConfigurationImportSelector.class})

作用:给容器导入组件AutoConfigurationImportSelector:自动配置导入选择器

1、查看AutoConfigurationImportSelector这个类的源码:里面有个方法getCandidateConfigurations

/**	 * Return the auto-configuration class names that should be considered. By default	 * this method will load candidates using {@link SpringFactoriesLoader} with	 * {@link #getSpringFactoriesLoaderFactoryClass()}.	 * @param metadata the source metadata	 * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation	 * attributes}	 * @return a list of candidate configurations	 *///获得候选的配置	protected List
getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
//这里的getSpringFactoriesLoaderFactoryClass()方法 //返回的就是我们最开始看的启动自动导入配置文件的注解类;EnableAutoConfiguration List
configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }

2、这个方法调用了SpringFactoriesLoader这个类的静态的方法!,进入loadFactoryNames方法内

/**	 * Load the fully qualified class names of factory implementations of the	 * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given	 * class loader.	 * @param factoryType the interface or abstract class representing the factory	 * @param classLoader the ClassLoader to use for loading resources; can be	 * {@code null} to use the default	 * @throws IllegalArgumentException if an error occurs while loading factory names	 * @see #loadFactories	 */	public static List
loadFactoryNames(Class
factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName(); //这里有调用来LoadSpringFactories 方法 return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList()); }

3、继续查看loadSpringFactories方法

private static Map
> loadSpringFactories(@Nullable ClassLoader classLoader) {
//获得classLoader , 我们返回可以看到这里得到的就是EnableAutoConfiguration标注的类本身 MultiValueMap
result = (MultiValueMap)cache.get(classLoader); if (result != null) {
return result; } else {
try {
//去获取一个资源 "META-INF/spring.factories" Enumeration
urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories"); LinkedMultiValueMap result = new LinkedMultiValueMap(); //将读取到的资源遍历,封装成为一个Properties while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); Iterator var6 = properties.entrySet().iterator(); while(var6.hasNext()) {
Entry
entry = (Entry)var6.next(); String factoryClassName = ((String)entry.getKey()).trim(); String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue()); int var10 = var9.length; for(int var11 = 0; var11 < var10; ++var11) {
String factoryName = var9[var11]; result.add(factoryClassName, factoryName.trim()); } } } cache.put(classLoader, result); return result; } catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13); } }}

4、注意:spring.factories

在这里插入图片描述

在这里插入图片描述

自动配置真正实现是从classpath中搜寻所有的META-INF/spring.factories配置文件 ,并将其中对应的 org.springframework.boot.autoconfigure. 包下的配置项,通过反射实例化为对应标注了 @Configuration的JavaConfig形式的IOC容器配置类 , 然后将这些都汇总成为一个实例并加载到IOC容器中。

结论:

  1. SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值
  2. 将这些值作为自动配置类导入容器 , 自动配置类就生效 , 帮我们进行自动配置工作;
  3. 整个J2EE的整体解决方案和自动配置都在springboot-autoconfigure的jar包中;
  4. 它会给容器中导入非常多的自动配置类 (xxxAutoConfiguration), 就是给容器中导入这个场景需要的所有组件 , 并配置好这些组件 ;
  5. 有了自动配置类 , 免去了我们手动编写配置注入功能组件等的工作;

5、SpringBoot的运行原理

SpringApplication

5.1不简单的方法

最初以为就是运行了一个main方法,没想到却开启了一个服务;

@SpringBootApplicationpublic class SpringApplication {
public static void main(String[] args) {
SpringApplication.run(SpringApplication.class, args); }}

5.2SpringApplication.run分析

分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;

5.2.1SpringApplication

这个类主要做了以下四件事情:

1、推断应用的类型是普通的项目还是Web项目

2、查找并加载所有可用初始化器 , 设置到initializers属性中

3、找出所有的应用程序监听器,设置到listeners属性中

4、推断并设置main方法的定义类,找到运行的主类

查看构造器:

public SpringApplication(ResourceLoader resourceLoader, Class
... primarySources) {
this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = getBootstrapRegistryInitializersFromSpringFactories(); setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); }

5.2.2run方法流程分析

在这里插入图片描述

转载地址:http://efcki.baihongyu.com/

你可能感兴趣的文章
Android&nbsp;HAL实例解析
查看>>
2011年06月21日
查看>>
Android&nbsp;HAL实例解析
查看>>
在驱动模块初始化函数中实现设备节…
查看>>
在驱动模块初始化函数中实现设备节…
查看>>
synchronized(this)的意思是:
查看>>
synchronized(this)的意思是:
查看>>
Android&nbsp;USB&nbsp;驱动分析
查看>>
Android&nbsp;Sensor传感器系统架构初探
查看>>
Android&nbsp;Sensor传感器系统架构初探
查看>>
Sensor传感器源码的阅读与应用开发…
查看>>
Sensor传感器源码的阅读与应用开发…
查看>>
Android传感器编程入门
查看>>
Android传感器编程入门
查看>>
Android的传感器HAL层的书写---基…
查看>>
Linux下android内核编译
查看>>
emulator使用方法
查看>>
emulator使用方法
查看>>
C&nbsp;语言&nbsp;undefined&nbsp;reference&nbsp;to&nbsp;&#039;s…
查看>>
动态链接库
查看>>