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;

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 卷积及理解图像卷积操作的意义

    卷积及理解图像卷积操作的意义转载:http://blog.csdn.net/chaipp0607/article/details/72236892     https://www.zhihu.com/question/22298352   在图像处理领域,我们经常能听到滤波,卷积之类的词,其实他们都可以看做一种图像的卷积操作,相对应的卷积核,卷积模板,滤波器,滤波模板,扫描窗其实也都是同一个东西。下面我们进一步讨论…

    2022年5月28日
    32
  • 去掉dedecms底部调用cfg_powerby

    去掉dedecms底部调用cfg_powerby**使用dedecms做网站,首页底部调cfg_powerby的时候出现powerbydedecms的链接信息。****文件路径:include/dedesql.class.php第588到第592行代码删除即可,代码如下图:**

    2022年7月15日
    14
  • IntelliJ IDEA优秀插件(编程通用)「建议收藏」

    IntelliJ IDEA优秀插件(编程通用)「建议收藏」一、IntelliJIDEA开发最近大部分开发IDE工具都切换到了,所以也花了点心思去找了相关的插件。这里整理的适合各种语言开发的通用插件,也排除掉IntelliJIDEA自带的常用插件了(有些插件在安装IntelliJIDEA的时候可以安装)。二、IDEA插件安装IDEA的插件安装非常简单,对于很多插件来说,只要你知道插件的名字就可以在IDEA里面直接安装。Preferences—>Pl

    2022年8月31日
    4
  • signature=26e3fa40cff08d52a53392bd149aa17b,Window Element, a Profiled Pultruded Panel, a System of a…

    signature=26e3fa40cff08d52a53392bd149aa17b,Window Element, a Profiled Pultruded Panel, a System of a…Thepresentinventiongenerallyrelatestothetechnicalfieldofhousesandbuildingsandtechniquesofbuildinghousesandbuildingsandmoreparticularlyrelatestonovelwindowelementsandpanels…

    2022年6月9日
    32
  • openfire 使用已有的数据库作为用户认证数据库 Custom Database Integration Guide「建议收藏」

    openfire 使用已有的数据库作为用户认证数据库 Custom Database Integration Guide

    2022年3月3日
    351
  • a算法解决八数码实验报告_人工智能常用算法模型

    a算法解决八数码实验报告_人工智能常用算法模型实验一A*算法求解8数码问题一、实验目的熟悉和掌握启发式搜索的定义、估价函数和算法过程,并利用A*算法求解N数码难题,理解求解流程和搜索顺序。二、实验原理A*算法是一种启发式图搜索算法,其特点在于对估价函数的定义上。对于一般的启发式图搜索,总是选择估价函数f值最小的节点作为扩展节点。因此,f是根据需要找到一条最小代价路径的观点来估算节点的,所以,可考虑每个节点n的估价函数值为两个分量:从起始节点到节点n的实际代价g(n)以及从节点n到达目标节点的估价代价h(n),且hn≤h*n,h*n

    2025年6月14日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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