SpringBoot-startup configuration principle
1. Startup process:
Several important event callback mechanisms
The following two are configured in META-INF/spring.factories:
- ApplicationContextInitializer
- SpringApplicationRunListener
The following two are configured in the ioc container
- ApplicationRunner
- CommandLineRunner
1. Create SpringApplication:
Starting a SpringBoot application will first create a SpringApplication, and then call the run method.
new SpringApplication (main program class)
- Determine whether web application
- Load and save all ApplicationContextInitializer (META-INF/spring.factories),
- Load and save all ApplicationListener
- Get the main program class
Creating SpringApplication is actually calling the constructor of SpringApplication, and completing the application type judgment and loading of Initializers, Listeners, etc. in it.
(1) webApplicationType: returns the type of the current web application.
None: non-web application starts
SERVLET: servlet-based web application and uses embedded server
REACTIVE: non-blocking
(2) Initializer and listener loading
setInitializers
: load the initializer
setListeners
from META-INF/spring.factories: load the listener from META-INF/spring.factories
Many packages have spring.factories, the following is an example of the autoconfiguration package:
After startup, the initializer and listener successfully loaded
(3) deduceMainApplicationClass()
Look at the passed class, which class has a main method, and which class is the main program.
2、run
run()
- Call back all the starting of SpringApplicationRunListener (META-INF/spring.factories)
- Get ApplicationArguments
- Prepare environment & callback environmentPrepared of all listeners (SpringApplicationRunListener)
- Print banner information
- Create ioc container object (web environment container or ordinary environment container)
- Prepare the environment
- 执行ApplicationContextInitializer. initialize()
- Listener SpringApplicationRunListener callback contextPrepared
- Load main configuration class definition information
- Listener SpringApplicationRunListener callback contextLoaded
- Refresh and start the IOC container;
- Scan and load components in all containers (including all EnableAutoConfiguration components obtained from META-INF/spring.factories)
- Call back all the run methods of ApplicationRunner and CommandLineRunner in the container
- Listener SpringApplicationRunListener callback started method and running method
The complete flow of the run method:
2. Event monitoring mechanism test
The following two need to be configured in META-INF/spring.factories:
- ApplicationContextInitializer
- SpringApplicationRunListener
The following two configurations can be injected into the ioc container
- ApplicationRunner
- CommandLineRunner