美文网首页
spring boot 启动源码解析

spring boot 启动源码解析

作者: 小蜗牛Aaron | 来源:发表于2020-09-26 15:34 被阅读0次
public static void main(String[] args) {
    // 启动入口
    SpringApplication.run(TheleafApplication.class, args);
}
// 静态方法 
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
        return run(new Class<?>[] { primarySource }, args);
    }

构造方法

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();
        // 从springfactories文件中加载初始化器
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 从springfactories中加载监听器
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 推断main方法所在的类
        this.mainApplicationClass = deduceMainApplicationClass();
    }

spring应用类型

/**
     * The application should not run as a web application and should not start an
     * embedded web server.
     */
//非web应用
    NONE,

    /**
     * The application should run as a servlet-based web application and should start an
     * embedded servlet web server.
     */
// servlet web 应用
    SERVLET,

    /**
     * The application should run as a reactive web application and should start an
     * embedded reactive web server.
     */
// 
    REACTIVE;

run方法分析

public ConfigurableApplicationContext run(String... args) {
        // 计时器
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 要返回的应用上下文
        ConfigurableApplicationContext context = null;
        // 空的异常报告器
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        // 这里是linux中没有图像输入的设置 headless
        configureHeadlessProperty();
        // 这里是加载运行时的监听器 详细分析见下
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting(this.mainApplicationClass);
        try {
            // 处理启动程序中的参数
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            // 准备程序所需的环境
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            // 设置一些不需要的bean
            configureIgnoreBeanInfo(environment);
            // 打印标志
            Banner printedBanner = printBanner(environment);
            // 创建应用上下文
            context = createApplicationContext();
            // 设置启动步骤器
            context.setApplicationStartup(this.applicationStartup);
            // 给异常报告器赋值
            exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class<?>[] { ConfigurableApplicationContext.class }, context);
            // 准备上下文
            prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            // 刷新上下文
            refreshContext(context);
            // 刷新之后
            afterRefresh(context, applicationArguments);
            // 停止计时器
            stopWatch.stop();
            // 日志打印
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            // 监听器
            listeners.started(context);
            // 执行所有runner运行器
            callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

        try {
            // 发布应用上下文就绪事件
            listeners.running(context);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, null);
            throw new IllegalStateException(ex);
        }
        return context;
    }

加载运行时的监听器

// 这里是加载运行时的监听器 详细分析见下
        SpringApplicationRunListeners listeners = getRunListeners(args);
private SpringApplicationRunListeners getRunListeners(String[] args) {
        // 组装从spring.factories文件中配置的类的构造方法参数类型
        Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
        // 新建返回值
        return new SpringApplicationRunListeners(logger,
                getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
                this.applicationStartup);
    }
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        // 获取类加载器
        ClassLoader classLoader = getClassLoader();
        // Use names and ensure unique to protect against duplicates
        // 从文件中加载类名
        Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        // 实例化
        List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        // 排序
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
            ClassLoader classLoader, Object[] args, Set<String> names) {
        List<T> instances = new ArrayList<>(names.size());
        for (String name : names) {
            try {
                // 编译获取类
                Class<?> instanceClass = ClassUtils.forName(name, classLoader);
                Assert.isAssignable(type, instanceClass);
                // 获取构造方法
                Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
                // 实例化
                T instance = (T) BeanUtils.instantiateClass(constructor, args);
                instances.add(instance);
            }
            catch (Throwable ex) {
                throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
            }
        }
        return instances;
    }

EventPublishingRunListener 的ApplicationStartingEvent事件触发的动作

RestartApplicationListener 重启器 用于重启应用 devtools中使用 实现热部署
LoggingApplicationListener 日志初始化器 可以根据配置决定使用哪一种日志系统

对于一些耗时的任务使用一个后台线程尽早触发它们开始执行初始化,这是Springboot的缺省行为。这些初始化动作也可以叫做预初始化。 设置系统属性spring.backgroundpreinitializer.ignore为true可以禁用该机制。 该机制被禁用时,相应的初始化任务会发生在前台线程。


相关文章

网友评论

      本文标题:spring boot 启动源码解析

      本文链接:https://www.haomeiwen.com/subject/qbafyktx.html