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
loador
Configure, parse command line parameters, prepare
ConfigurableEnvironment
。
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, executeCommandLineRunner
andApplicationRunner
。
Startup is complete
When the application is ready, triggerApplicationReadyEvent
, officially enters operational state.
2. Core component analysis
2.1 Environmental preparation
Spring Boot ByConfigurableEnvironment
Unified management of environment variables, configuration files, system attributes and other information.
Loading order:
- System properties (e.g.
-D
parameter). - Environment variables (
()
)。 - Configuration file (
or
)。
- Command line parameters (
args
)。
Expansion Point:
It can be achieved byEnvironmentPostProcessor
Customize 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 as
Environment
andResourceLoader
。 - Load the bean definition and prepare the application's dependency graph.
2.3 Bean loading and initialization
Scan and load:
pass@ComponentScan
Scan the package path and load all labels@Component
、@Service
、@Repository
、@Controller
Classes with annotations.
Lifecycle callback:
During initialization, Spring will call the following interface or annotation:
-
InitializingBean
ofafterPropertiesSet()
。 -
@PostConstruct
method.
AOP Agent:
according to@EnableAspectJAutoProxy
Automatically create proxy for eligible beans.
2.4 Automatic configuration
Spring Boot's "magic" comes from the automatic configuration mechanism to a large extent, through@EnableAutoConfiguration
accomplish.
Implementation principle:
Spring BootFile loads all auto-configuration classes.
Core category:@ConditionalOnClass
、@ConditionalOnProperty
etc. Annotation to control whether to load and configure automatically.
Expansion Point:
It can be achieved byAutoConfigurationImportFilter
Customize 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 BoothandleRunFailure
The method centrally handles exceptions during startup:
How to deal with it:
- Print the error log.
- Call registered
SpringApplicationRunListener
offailed()
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:initialization
SpringApplication
, load environment and listeners. -
Context Loading:create
ApplicationContext
, 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, call
Runner
Interface, 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!