SpringBoot启动流程是什么

发布时间:2023-05-05 15:37:49 作者:iii
来源:亿速云 阅读:115

本篇内容主要讲解“SpringBoot启动流程是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot启动流程是什么”吧!

SpringBoot启动过程简介

SpringBoot应用程序的启动过程可以分为以下几个步骤:

加载应用程序上下文

SpringBoot 应用程序的上下文是一个包含所有应用程序组件的容器。在启动过程中,SpringBoot 会加载并初始化这个容器。

这个步骤的源代码在SpringApplication类中。具体来说,SpringApplication类的run方法是这个过程的入口点。在这个方法中,Spring Boot会通过调用createApplicationContext方法来创建应用程序上下文。

下面是createApplicationContext方法的源代码:

protected ConfigurableApplicationContext createApplicationContext() {
    Class<?> contextClass = this.applicationContextClass;
    if (contextClass == null) {
        try {
            switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_SERVLET_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 to create a default ApplicationContext, " +
                    "please specify an ApplicationContextClass", ex);
        }
    }
    return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

在这个方法中,SpringBoot 会根据应用程序类型(Servlet或Reactive)选择合适的上下文类。然后,它会使用 Java 反射机制来实例化这个类并返回一个可配置的应用程序上下文对象。

扫描应用程序中的所有组件

在上一步中,SpringBoot创建了应用程序上下文。在这一步中,SpringBoot会扫描应用程序中的所有组件并将它们注册到应用程序上下文中。

这个步骤的源代码在SpringApplication类中的scan方法中。具体来说,在这个方法中,SpringBoot 会创建一个SpringBootBeanDefinitionScanner对象,并使用它来扫描应用程序中的所有组件。

下面是scan方法的源代码:

private void scan(String... basePackages) {
    if (ObjectUtils.isEmpty(basePackages)) {
        return;
    }
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            this.includeFilters, this.excludeFilters, this.resourceLoader);
    scanner.setResourceLoader(this.resourceLoader);
    scanner.setEnvironment(this.environment);
    scanner.setIncludeAnnotationConfig(this.useAnnotatedConfig);
    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        @Override
        protected boolean matchClassName(String className) {
            return getExcludeClassNames().contains(className);
        }
    });
    for (String basePackage : basePackages) {
        scanner.findCandidateComponents(basePackage).forEach(this.componentDefinitions::add);
    }
}

在这个方法中,SpringBoot 会创建一个ClassPathScanningCandidateComponentProvider对象,并使用它来扫描应用程序中的所有组件。这个对象会扫描指定包路径下的所有类,并将它们转换为 Spring 的 Bean 定义。这些 Bean 定义将被注册到应用程序上下文中。

自动配置应用程序环境

在上一步中,SpringBoot将应用程序中的所有组件注册到应用程序上下文中。在这一步中,SpringBoot将自动配置应用程序环境,包括配置数据源、事务管理器、JPA等。

这个步骤的源代码在SpringApplication类中的configureEnvironment方法中。在这个方法中,Spring Boot会创建一个SpringApplicationRunListeners对象,并使用它来配置应用程序环境。

下面是configureEnvironment方法的源代码:

private void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
    if (this.addCommandLineProperties) {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        environment.getPropertySources().addLast(new CommandLinePropertySource(applicationArguments));
    }
    this.listeners.environmentPrepared(environment);
    if (this.logStartupInfo) {
        this.logStartupInfo(environment);
    }
    ConfigurationPropertySources.attach(environment);
    Binder.get(environment).bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(this.sources));
    if (!this.isCustomEnvironment) {
        EnvironmentConverter.configureEnvironment(environment, this.deduceEnvironmentClass());
    }
    this.listeners.environmentPrepared(environment);
}

在这个方法中,SpringBoot 会创建一个ApplicationArguments对象,并将其转换为一个命令行属性源。然后,它会调用listeners中的environmentPrepared方法来通知应用程序环境已经准备好了。随后,SpringBoot 会绑定属性源到应用程序环境中,并调用listeners中的environmentPrepared方法来通知应用程序环境已经准备好了。

启动嵌入式Web服务器

在上一步中,SpringBoot 将应用程序环境自动配置完成。在这一步中,SpringBoot 将启动嵌入式Web服务器,以便应用程序能够提供 Web 服务。

这个步骤的源代码在SpringApplication类中的run方法中。具体来说,在这个方法中,SpringBoot 会根据应用程序类型(Servlet或Reactive)选择合适的嵌入式Web服务器,并使用它来启动应用程序。

下面是run方法的源代码:

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();
        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);
        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;
}

在这个方法中,SpringBoot 会使用一个StopWatch对象来计算应用程序启动时间。然后,它会调用listeners中的starting方法来通知应用程序即将启动。接着,SpringBoot 会准备应用程序环境,并使用它来创建应用程序上下文。随后,SpringBoot 会调用listeners中的started方法来通知应用程序已经启动。最后,SpringBoot 会调用callRunners方法来运行所有的CommandLineRunnerApplicationRunner组件。

到此,相信大家对“SpringBoot启动流程是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. SpringBoot整合SpringDataRedis的全过程分析
  2. Springboot如何在有参构造方法类中使用@Value注解取值

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:Python的数组是什么及怎么应用

下一篇:c++怎么使用单例模式实现命名空间函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》