springboot源码解析详细版

springboot源码解析详细版springboot源码解析(转)SpringBoot的入口类@SpringBootApplicationpublicclassStartupApplication{publicstaticvoidmain(String[]args){SpringApplication.run(StartupApplication.class,args)…

大家好,又见面了,我是你们的朋友全栈君。

springboot源码解析(转)

一.Spring Boot 的入口类

@SpringBootApplication
public class StartupApplication { 
   

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

第一个参数 resourceLoader:资源加载器

第二个参数 primarySources:加载的主要资源类

	@SuppressWarnings({ 
    "unchecked", "rawtypes" })
	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { 
   
		// 1、资源初始化资源加载器为 null,默认为空
		this.resourceLoader = resourceLoader;
		// 2、断言主要加载资源类不能为 null,否则报错
		Assert.notNull(primarySources, "PrimarySources must not be null");
		// 3、初始化主要加载资源类集合并去重
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		// 4、推断当前 WEB 应用类型,一共有三种:
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		//5、设置应用上线文初始化器,从"META-INF/spring.factories"读取ApplicationContextInitializer类的实例名称集合并去重,并进行set去重。(一共4个)
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
		// 6、设置监听器,从"META-INF/spring.factories"读取ApplicationListener类的实例名称集合并去重,并进行set去重。(一共10个)
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		// 7、推断主入口应用类,通过当前调用栈,获取Main方法所在类,并赋值给mainApplicationClass。
		this.mainApplicationClass = deduceMainApplicationClass();
	}

1.详细看看deduceFromClasspath方法的实现:

static WebApplicationType deduceFromClasspath() { 
   
    if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
            && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
            && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) { 
   
        return WebApplicationType.REACTIVE;
    }
    for (String className : SERVLET_INDICATOR_CLASSES) { 
   
        if (!ClassUtils.isPresent(className, null)) { 
   
            return WebApplicationType.NONE;
        }
    }
    return WebApplicationType.SERVLET;
}       
public enum WebApplicationType { 
   

    //非 WEB 项目
    NONE,

    //SERVLET WEB 项目
    SERVLET,

    //响应式 WEB 项目
    REACTIVE;
}

二.springboot启动类

public ConfigurableApplicationContext run(String... args) { 

// 1、创建并启动计时监控类
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 2、初始化应用上下文和异常报告集合
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 3、设置系统属性 `java.awt.headless` 的值,默认值为:true,用于运行headless服务器,进行简单的图像处理
configureHeadlessProperty();
// 4、创建所有 Spring 运行监听器并发布应用启动事件
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try { 

// 5、初始化默认应用参数类
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
// 6、根据运行监听器和应用参数来准备 Spring 环境
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
// 7、创建 Banner 打印类
Banner printedBanner = printBanner(environment);
// 8、创建应用上下文
context = createApplicationContext();
// 9、准备异常报告器
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { 
 ConfigurableApplicationContext.class }, context);
// 10、准备应用上下文
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
// 11、刷新应用上下文
refreshContext(context);
// 12、应用上下文刷新后置处理
afterRefresh(context, applicationArguments);
// 13、停止计时监控类
stopWatch.stop();
// 14、输出日志记录执行主类名、时间信息
if (this.logStartupInfo) { 

new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
// 15、发布应用上下文启动完成事件
listeners.started(context);
// 16、执行所有 Runner 运行器
callRunners(context, applicationArguments);
}
catch (Throwable ex) { 

handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try { 

// 17、发布应用上下文就绪事件
listeners.running(context);
}
catch (Throwable ex) { 

handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
// 18、返回应用上下文
return context;
}

三.启动详解

1、创建并启动计时监控类

StopWatch stopWatch = new StopWatch();
stopWatch.start();

来看下这个计时监控类 StopWatch 的相关源码:

作用

  • 首先记录了当前任务的名称,默认为空字符串,然后记录当前 Spring Boot 应用启动的开始时间
public void start() throws IllegalStateException { 

start("");
}
public void start(String taskName) throws IllegalStateException { 

if (this.currentTaskName != null) { 

throw new IllegalStateException("Can't start StopWatch: it's already running");
}
this.currentTaskName = taskName;
this.startTimeMillis = System.currentTimeMillis();
}

2、初始化应用上下文和异常报告集合

ConfigurableApplicationContext context = null;
Collection exceptionReporters = new
ArrayList<>();

3、设置系统属性 java.awt.headless 的值

configureHeadlessProperty();

4、创建所有 Spring 运行监听器并发布应用启动事件

SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();

来看下创建 Spring 运行监听器相关的源码:

private SpringApplicationRunListeners getRunListeners(String[] args) { 

Class<?>[] types = new Class<?>[] { 
 SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
SpringApplicationRunListener.class, types, this, args));
}
SpringApplicationRunListeners(Log log,
Collection<? extends SpringApplicationRunListener> listeners) { 

this.log = log;
this.listeners = new ArrayList<>(listeners);
}

5、初始化默认应用参数类

ApplicationArguments applicationArguments = newDefaultApplicationArguments(String[] args);

6.下面我们主要来看下准备环境的 prepareEnvironment 源码:

作用:

  • 获取(或者创建)应用环境
  • 配置应用环境
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) { 

// 6.1) 获取(或者创建)应用环境
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 6.2) 配置应用环境
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (this.webApplicationType == WebApplicationType.NONE) { 

environment = new EnvironmentConverter(getClassLoader())
.convertToStandardEnvironmentIfNecessary(environment);
}
ConfigurationPropertySources.attach(environment);
return environment;
}
//6.1) 获取(或者创建)应用环境
private ConfigurableEnvironment getOrCreateEnvironment() { 

if (this.environment != null) { 

return this.environment;
}
if (this.webApplicationType == WebApplicationType.SERVLET) { 

return new StandardServletEnvironment();
}
return new StandardEnvironment();
}
//这里分为标准 Servlet 环境和标准环境。
//6.2) 配置应用环境
protected void configureEnvironment(ConfigurableEnvironment environment,
String[] args) { 

configurePropertySources(environment, args);
configureProfiles(environment, args);
}

6.2)这里分为以下两步来配置应用环境。

配置 property sources
配置 Profiles
这里主要处理所有 property sources 配置和 profiles配置。

7、创建 Banner 打印类

Banner printedBanner = printBanner(environment);

8、创建应用上下文

context = createApplicationContext();

来看下 createApplicationContext() 方法的源码:
作用:

  • 根据不同的应用类型初始化不同的上下文应用类。
protected ConfigurableApplicationContext createApplicationContext() { 

Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) { 

try { 

switch (this.webApplicationType) { 

case SERVLET:
contextClass = Class.forName(DEFAULT_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);
}

9、准备异常报告器

exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);

10、准备应用上下文

prepareContext(context, environment, listeners, applicationArguments,
printedBanner);

来看下 prepareContext() 方法的源码:

private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) { 

// 10.1)绑定环境到上下文
context.setEnvironment(environment);
// 10.2)配置上下文的 bean 生成器及资源加载器
postProcessApplicationContext(context);
// 10.3)为上下文应用所有初始化器
applyInitializers(context);
// 10.4)触发所有 SpringApplicationRunListener 监听器的 contextPrepared 事件方法
listeners.contextPrepared(context);
// 10.5)记录启动日志
if (this.logStartupInfo) { 

logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// 10.6)注册两个特殊的单例bean
context.getBeanFactory().registerSingleton("springApplicationArguments",
applicationArguments);
if (printedBanner != null) { 

context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
}
// 10.7)加载所有资源
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
// 10.8)触发所有 SpringApplicationRunListener 监听器的 contextLoaded 事件方法
listeners.contextLoaded(context);
}

11、刷新应用上下文
refreshContext(context);
这个主要是刷新 Spring 的应用上下文,源码如下,不详细说明。

private void refreshContext(ConfigurableApplicationContext context) { 

refresh(context);
if (this.registerShutdownHook) { 

try { 

context.registerShutdownHook();
}
catch (AccessControlException ex) { 

// Not allowed in some environments.
}
}
}

12、应用上下文刷新后置处理
afterRefresh(context, applicationArguments);
看了下这个方法的源码是空的,目前可以做一些自定义的后置处理操作。

protected void afterRefresh(ConfigurableApplicationContext context,
ApplicationArguments args) { 

}

13、停止计时监控类

stopWatch.stop();
public void stop() throws IllegalStateException { 

if (this.currentTaskName == null) { 

throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
long lastTime = System.currentTimeMillis() - this.startTimeMillis;
this.totalTimeMillis += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) { 

this.taskList.add(this.lastTaskInfo);
}
++this.taskCount;
this.currentTaskName = null;
}

计时监听器停止,并统计一些任务执行信息。

14、输出日志记录执行主类名、时间信息

if (this.logStartupInfo) { 

new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}

15、发布应用上下文启动完成事件

listeners.started(context);

触发所有 SpringApplicationRunListener 监听器的 started 事件方法。

16、执行所有 Runner 运行器

callRunners(context, applicationArguments);

private void callRunners(ApplicationContext context, ApplicationArguments args) { 

List<Object> runners = new ArrayList<>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) { 

if (runner instanceof ApplicationRunner) { 

callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) { 

callRunner((CommandLineRunner) runner, args);
}
}
}

执行所有 ApplicationRunner 和 CommandLineRunner 这两种运行器,不详细展开了。

17、发布应用上下文就绪事件

listeners.running(context);

触发所有 SpringApplicationRunListener 监听器的 running 事件方法。

18、返回应用上下文

return context;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/133474.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Python数组的使用_算法高效性

    Python数组的使用_算法高效性如果我们需要一个只包含数字的列表,那么使用数组方式比list方式更高效。而且数组还支持所有跟可变序列有关的操作,比如移除列表中的一个元素(.pop)、插入元素(.insert)和在列表末尾一次性追加另一个序列中的多个值(.extend)。除此之外,数组还定义从文件读取(.frombytes)与写入(.tofile)的效率更高的方法。创建数组需要一个类型码,形如array(‘d’),这个类型码是用来表示在底层实现的C语言的数据类型。一般我们用的Python底层是用C语言编写实现的&n

  • double保留小数点后两位_double截取两位小数

    double保留小数点后两位_double截取两位小数publicclassDoubleTest{//保留两位小数第三位如果大于4会进一位(四舍五入)doublef=6.23556;/***使用精确小数BigDecimal*/publicvoidfun1(){BigDecimalbg=newBigDecimal(f);/…

    2022年10月20日
  • jupyter的代码能用pycharm运行吗_win10安装jupyter

    jupyter的代码能用pycharm运行吗_win10安装jupyter在Pycharm中安装及使用Jupyter(图文详解)文章目录在Pycharm中安装及使用Jupyter(图文详解)一、材料二、安装Jupyter三、配置Jupyter四、使用Jupyter1.使用Cell2.使用jupyterMarkdownPycharm更新了对Jupyter的功能支持,结合IntelliJ的自动补全代码,自动格式化代码,执行调试…

  • 2022pycharm激活码【最新永久激活】

    (2022pycharm激活码)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.cn/100143.html…

  • python报错no module named_pycharm报错no module named

    python报错no module named_pycharm报错no module namedpycharm在运行时出现“ModuleNotFoundError:Nomodulenamed‘pygame’”错误的解决方法例如:(出现这样子的错误,再出错的地方点击installpygame后,代码还是会出现上面的错误,这时候,我手动安装之后代码就能正常运行了。)手动安装pygame:通过文件—设置—项目解释器(File-setting-Projectinterpreter),点击“+”,搜索pygame,点击左下角的安装即可。如下图所示:右侧下方点击“+”:在搜索框

  • 关于开源的RTP——jrtplib的使用

    关于开源的RTP——jrtplib的使用

    2021年11月28日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号