SoFunction
Updated on 2025-03-04

Spring Boot startup process analysis

Spring Boot is a simplified Spring application development framework that provides developers with out-of-the-box features with the concept of "convention over configuration". During Spring Boot running,()The method is the core of the entire startup process. This article will analyze its internal implementation in detail to help you deeply understand the startup mechanism of Spring Boot.

1. The main steps for Spring Boot startup

Spring Boot starts by()Method driver, its core code is as follows:

(, args);

The operation process of this method can be divided into the following main steps:

Initialize SpringApplication
Determines the application type (Servlet/Reactive/non-Web), loading environment and listeners.

Prepare for the operating environment
loadorConfigure, parse command line parameters, prepareConfigurableEnvironment

Create an application context
Create corresponding application typeApplicationContext,For example:

AnnotationConfigServletWebServerApplicationContext(Servlet application)ReactiveWebServerApplicationContext(Reactive application)

Refresh the context
Complete the bean loading, dependency injection, AOP proxy and other operations, and start the embedded web server (if needed).

Notify listeners and execute extension points
Trigger life cycle event, executeCommandLineRunnerandApplicationRunner

Startup is complete
When the application is ready, triggerApplicationReadyEvent, officially enters operational state.

2. Core component analysis

2.1 Environmental preparation

Spring Boot ByConfigurableEnvironmentUnified management of environment variables, configuration files, system attributes and other information.

Loading order

  • System properties (e.g.-Dparameter).
  • Environment variables (())。
  • Configuration file (or)。
  • Command line parameters (args)。

Expansion Point
It can be achieved byEnvironmentPostProcessorCustomize environment variable loading logic.

2.2 Context creation

Spring Boot Select the appropriate one according to the application typeApplicationContext

Application Type Context Type illustrate
Servlet Application AnnotationConfigServletWebServerApplicationContext The default web application context.
Reactive Apps ReactiveWebServerApplicationContext Responsive programming application context.
Non-Web application GenericApplicationContext Normal Java application context.

When the context is created, the following work is also done:

  • Register basic components such asEnvironmentandResourceLoader
  • Load the bean definition and prepare the application's dependency graph.

2.3 Bean loading and initialization

Scan and load
pass@ComponentScanScan the package path and load all labels@Component@Service@Repository@ControllerClasses with annotations.

Lifecycle callback
During initialization, Spring will call the following interface or annotation:

  • InitializingBeanofafterPropertiesSet()
  • @PostConstructmethod.

AOP Agent
according to@EnableAspectJAutoProxyAutomatically create proxy for eligible beans.

2.4 Automatic configuration

Spring Boot's "magic" comes from the automatic configuration mechanism to a large extent, through@EnableAutoConfigurationaccomplish.

Implementation principle
Spring BootFile loads all auto-configuration classes.

Core category
@ConditionalOnClass@ConditionalOnPropertyetc. Annotation to control whether to load and configure automatically.

Expansion Point
It can be achieved byAutoConfigurationImportFilterCustomize the loading behavior of automatic configuration classes.

3. Lifecycle Events

Spring Boot will trigger the following events during startup, and developers can customize logical processing through listeners:

For example, monitorApplicationReadyEvent

Event name Trigger timing
ApplicationStartingEvent The application starts.
ApplicationEnvironmentPreparedEvent Environment variables are ready to be completed.
ApplicationPreparedEvent The context is ready to be completed but not refreshed.
ApplicationStartedEvent The context refresh is complete.
ApplicationReadyEvent The application is fully launched and ready to receive the request.
ApplicationFailedEvent Startup failed.

For example, monitorApplicationReadyEvent

@Component
public class MyApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ("Application is ready!");
    }
}

4. Start the exception handling mechanism

Spring BoothandleRunFailureThe method centrally handles exceptions during startup:

How to deal with it

  • Print the error log.
  • Call registeredSpringApplicationRunListeneroffailed()method.
  • Close the application context and release the resource.

Common exceptions

  • BeanDefinitionStoreException: Bean definition loading error.
  • UnsatisfiedDependencyException: Dependency injection failed.
  • IllegalStateException: The context state is illegal.

5. Summary

Spring Boot's startup process is highly modular, with a fixed main process and providing developers with rich expansion points. The main process can be summarized as:

  • Preparation phase:initializationSpringApplication, load environment and listeners.
  • Context Loading:createApplicationContext, load configuration and bean definition.
  • Context refresh: Complete the dependency injection and initialization of the bean and start the embedded server.
  • Extensions and Callbacks: Notify listener, callRunnerInterface, trigger life cycle events.

By understanding the Spring Boot startup process, you can debug problems more efficiently, optimize startup performance, and even customize startup behavior, so you can better control your application.

This is the end of this article about the detailed explanation of the Spring Boot startup process. For more related contents of the Spring Boot startup process, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!