【源码解析】SpringBoot的源码深入分析

news2024/9/21 2:33:37

SpringBoot源码分析

主流程

SpringBoot项目的组成是需要引入SpringBoot需要的依赖,另外启动类上添加@SpringBootApplication,主要是标明该类是启动类和实现自动装配,自动装配的原理详细可见,SpringBoot自动装配的实现原理。那么main方法的作用是什么?跟随着源码看一看呢。

SpringApplication#run(),新建了SpringApplication类,调用run方法。

    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return (new SpringApplication(primarySources)).run(args);
    }

SpringApplication构造方法。主要是定义了webApplicationType,是否是web环境,标注主类,根据SpringBoot的SPI获取到ApplicationContextInitializerApplicationListener

    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.sources = new LinkedHashSet();
        this.bannerMode = Mode.CONSOLE;
        this.logStartupInfo = true;
        this.addCommandLineProperties = true;
        this.addConversionService = true;
        this.headless = true;
        this.registerShutdownHook = true;
        this.additionalProfiles = Collections.emptySet();
        this.isCustomEnvironment = false;
        this.lazyInitialization = false;
        this.applicationContextFactory = ApplicationContextFactory.DEFAULT;
        this.applicationStartup = ApplicationStartup.DEFAULT;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        this.bootstrapRegistryInitializers = new ArrayList(this.getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

SpringApplication#run(java.lang.String...),核心主要是

  • 获取SpringApplicationRunListener,进行SpringBoot流程的不同生命周期的调用。
  • 创建了ConfigurableEnvironment,加载配置信息
  • 打印Banner信息
  • 根据应用类型创建ConfigurableApplicationContext
  • 刷新Spring容器
  • 调用Runner,主要是ApplicationRunnerCommandLineRunner
	public ConfigurableApplicationContext run(String... args) {
		long startTime = System.nanoTime();
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting(bootstrapContext, this.mainApplicationClass);
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			context.setApplicationStartup(this.applicationStartup);
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
			}
			listeners.started(context, timeTakenToStartup);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}
		try {
			Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
			listeners.ready(context, timeTakenToReady);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}

加载配置

SpringApplication#prepareEnvironment,创建应用环境。在listeners.environmentPrepared(bootstrapContext, environment);会进行配置文件的加载。

	private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
			DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
		// Create and configure the environment
		ConfigurableEnvironment environment = getOrCreateEnvironment();
		configureEnvironment(environment, applicationArguments.getSourceArgs());
		ConfigurationPropertySources.attach(environment);
		listeners.environmentPrepared(bootstrapContext, environment);
		DefaultPropertiesPropertySource.moveToEnd(environment);
		Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
				"Environment prefix cannot be set via properties.");
		bindToSpringApplication(environment);
		if (!this.isCustomEnvironment) {
			environment = convertEnvironment(environment);
		}
		ConfigurationPropertySources.attach(environment);
		return environment;
	}

ConfigFileApplicationListener会进行application.yml文件的解析,BootstrapApplicationListener读取 bootstrap.yml 文件的信息

刷新容器

AbstractApplicationContext#refresh。刷新容器的关键步骤有

  • 获取ConfigurableListableBeanFactory
  • invokeBeanFactoryPostProcessors,核心方法。ConfigurationClassPostProcessor会进行Bean的扫描,在Spring容器中创建不同BeanDefinition
  • 注册BeanPostProcessor
  • 国际化
  • 创建事件发布器
  • 如果是Web容器,会调用onRefresh方法,进行Web容器的启动
  • 注册监听器
  • finishBeanFactoryInitialization,核心方法。用于在Spring容器中真正生成实例Bean。
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// 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);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				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();
				contextRefresh.end();
			}
		}
	}

Web容器启动

ServletWebServerApplicationContext#onRefresh

	@Override
	protected void onRefresh() {
		super.onRefresh();
		try {
			createWebServer();
		}
		catch (Throwable ex) {
			throw new ApplicationContextException("Unable to start web server", ex);
		}
	}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/377945.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Docker基本介绍

最近需要将项目做成一个web应用并部署到多台服务器上&#xff0c;于是就简单学习了一下docker&#xff0c;做一下小小的记录。 1、简单介绍一下docker 我们经常遇到这样一个问题&#xff0c;自己写的代码在自己的电脑上运行的很流畅&#xff0c;在其他人电脑上就各种bug&…

Linux学习--常用命令vi/vim

linux平台的文本编辑器 vi/vim的使用 vi windows的记事本 vim Windows的notepad 基本上vi/vim共分为三种模式&#xff0c;命令模式(Command mode)&#xff0c;输入模式(Insert mode)&#xff0c;底线命令模式(Last line mode) vim使用流程 1、下载vim yum install vim …

【并发编程学习篇】深入理解CyclicBarrier

一、CyclicBarrier介绍 字面意思回环栅栏&#xff08;循环屏障&#xff09;&#xff0c;通过它可以实现让一组线程等待至某个状态&#xff08;屏障点&#xff09;之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后&#xff0c;CyclicBarrier可以被重用。 和Count…

动态规划:leetcode 70.爬楼梯、322.零钱兑换、279.完全平方数

leetcode 70.爬楼梯leetcode 322.零钱兑换leetcode 279.完全平方数leetcode 70.爬楼梯假设你正在爬楼梯。需要 n 阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f;注意&#xff1a;给定 n 是一个正整数。示例 1&#xff1a; 输入…

【C++】-- 智能指针

目录 智能指针意义 智能指针的使用及原理 RAII 智能指针的原理 std::auto_ptr std::auto_ptr的模拟实现 std::unique_ptr std::unique_ptr模拟实现 std::shared_ptr std::shared_ptr的模拟实现 循环引用问题 智能指针意义 #问&#xff1a;为什么需要智能指针&#…

R语言绘制SCI论文中常见的箱线散点图,并自动进行方差分析计算显著性水平

显著性标记箱线散点图 本篇笔记的内容是在R语言中利用ggplot2&#xff0c;ggsignif&#xff0c;ggsci&#xff0c;ggpubr等包制作箱线散点图&#xff0c;并计算指定变量之间的显著性水平&#xff0c;对不同分组进行特异性标记&#xff0c;最终效果如下。 加载R包 library(ggplo…

SQL注入漏洞利用(上)

SQL注入漏洞SQL注入漏洞SQL注入原理SQL注入带来的危害SQL注入分类数字型注入实操字符型注入实操类型检测and测试绕过密码&#xff1a;or 11 --搜索型注入实操SQL注入漏洞 攻击者利用Web应用程序对用户输入验证上的疏忽&#xff0c;在输入的数据中包含对某些数据库系统有特殊意…

离散数学笔记_第一章:逻辑和证明(2 )

1.2 命题逻辑的应用1.2.1 语句翻译 1.2.2 系统规范说明 1.2.3 布尔搜索 1.2.4 逻辑谜题泥巴孩子谜题骑士和流氓&#xff08;考研逻辑题&#xff09;1.1.2.5 逻辑电路1.2.1 语句翻译 &#x1f433;为啥要翻译语句&#xff1f; ➡因语言常常有二义性&#xff08;有歧义&#x…

Window.location 详细介绍

如果你需要获取网站的 URL 信息&#xff0c;那么 window.location 对象就是为你准备的。使用它提供的属性来获取当前页面地址的信息&#xff0c;或使用其方法进行某些页面的重定向或刷新。 https://www.samanthaming.com/tidbits/?filterJS#2 window.location.origin → htt…

Dbeaver连接Hive数据库操作指导

背景&#xff1a;由于工作需要&#xff0c;当前分析研究的数据基于Hadoop的Hive数据库中&#xff0c;且Hadoop服务端无权限进行操作且使用安全模式&#xff0c;在研究了Dbeaver、Squirrel和Hue三种连接Hive的工具&#xff0c;在无法绕开useKey认证的情况下&#xff0c;只能使用…

基于vscode开发vue项目的详细步骤教程

1、Vue下载安装步骤的详细教程(亲测有效) 1_水w的博客-CSDN博客 2、Vue下载安装步骤的详细教程(亲测有效) 2 安装与创建默认项目_水w的博客-CSDN博客 目录 五、vscode集成npm开发vue项目 1、vscode安装所需要的插件&#xff1a; 2、搭建一个vue小页面(入门vue) 3、大致理解…

近期常见组件漏洞更新:

&#xff08;1&#xff09;mysql 5.7 在2023年1月17日&#xff0c;发布了到5.7.41版本 mysql 8.0 在2023年1月17日&#xff0c;发布了到8.0.32版本 MySQL :: Download MySQL Community Serverhttps://dev.mysql.com/downloads/mysql/ &#xff08;2&#xff09;Tomcat8在202…

react react-redux数据共享学习记录

react react-redux数据共享1.目的2.数据共享版本2.1Person模块的添加2.1.1 Containers下的Person2.1.2 actions下的person.js2.1.3 reducers下的person.js2.2 store.js的改写&#xff01;2.3 组件中取出状态的时候&#xff0c;记得“取到位”3.纯函数1.目的 前面的react和reac…

精确光度预测计算工具:AGi32 Crack

什么是AGi32&#xff1f; AGi32首先是一种用于精确光度预测的计算工具&#xff1a;一种技术工具&#xff0c;可以计算任何情况下的照度&#xff0c;协助灯具放置和瞄准&#xff0c;并验证是否符合任意数量的照明标准。 然而&#xff0c;要增强对光度学结果的理解&#xff0c;还…

创建SpringBoot注意事项

作为一个java小白&#xff0c;你是否因为创建SpringBoot项目那些莫名其妙的错误搞得头皮发麻。不要慌张&#xff0c;这篇文章能帮你解决90%的问题【持续更新…】 本文结合创建SpringBoot项目的完整过程来讲 在idea中新建项目 虽然SpringBoot项目是由maven内核组成的&#xff0…

【Linux驱动】驱动设计硬件基础----串口、I2C、SPI、以太网接口、PCIE

1.前言 常见的外设接口与总线的工作方式&#xff0c;包括串口、I2C、SPI、USB、以太网接口、PCI和PCI-E、SD和SDIO等。 2.串口 RS-232、RS-422与RS-485都是串行数据接口标准&#xff0c;最初都是由电子工业协会&#xff08;EIA&#xff09;制订并发布的。 3.I2C I2C&…

canvas复习笔记(绘制直线、矩形、圆形、圆弧)

canvas 画一条直线 <body><canvasid"c"width"300"height"200"style"border: 1px solid #ccc;"></canvas> </body><script>// 2、获取 canvas 对象const cnv document.getElementById("c");…

数据结构与算法之Huffman tree(赫夫曼树 / 霍夫曼树 / 哈夫曼树 / 最优二叉树)

目录赫夫曼树概述定义构造赫夫曼树步骤代码实现赫夫曼树概述 HuffmanTree因为翻译不同所以有其他的名字&#xff1a;赫夫曼树、霍夫曼树、哈夫曼树 赫夫曼树又称最优二叉树&#xff0c;是一种带权路径长度最短的二叉树。所谓树的带权路径长度&#xff0c;就是树中所有的叶结点…

【IDEA】【工具】幸福感UP!开发常用的工具 插件/网站/软件

IDEA 插件 CodeGlance Pro —— 代码地图 CodeGlance是一款非常好用的代码地图插件&#xff0c;可以在代码编辑区的右侧生成一个竖向可拖动的代码缩略区&#xff0c;可以快速定位代码的同时&#xff0c;并且提供放大镜功能。 使用:可以通过Settings—>Other Settings—&g…

Linux学习(9.1)文件系统的简单操作

以下内容转载自鸟哥的Linux私房菜 原文&#xff1a;鸟哥的 Linux 私房菜 -- Linux 磁盘与文件系统管理 (vbird.org) 磁盘与目录的容量 df&#xff1a;列出文件系统的整体磁盘使用量&#xff1b;du&#xff1a;评估文件系统的磁盘使用量(常用在推估目录所占容量) df du 实体…