Source code analysis

In SpringApplication. Run (SystemmanageApplication. Class, args) entry a breakpoint, the debug.

Continue to Debug

New SpringApplication() calls the constructor and initializes it

  1. Determines whether the current type is Web
  2. Load all initializers
  3. Load all listeners
  4. Sets the main class for the program to run

Execute the run method

Locate the public ConfigurableApplicationContext run (String… Args) method, start analyzing

public ConfigurableApplicationContext run(String... args) {
    // Create and start the timing monitor class
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // Declare the application context object and exception report collection
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
    // Set the system property headless
    this.configureHeadlessProperty();
    // Create all Spring run listeners and publish application start events
    SpringApplicationRunListeners listeners = this.getRunListeners(args);
    listeners.starting();
    Collection exceptionReporters;
    try {
        // Process args parameters
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        // Prepare the environment
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        // Create a print class for Banner
        Banner printedBanner = this.printBanner(environment);
        // Create the application context
        context = this.createApplicationContext();
        // Instantiate the exception reporter
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
        // Prepare the application context
        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        // Refresh the application context
        this.refreshContext(context);
        // Handle the event after applying the context refresh
        this.afterRefresh(context, applicationArguments);
        // Stop the timer monitoring class
        stopWatch.stop();
        // Logs are generated to record the name and time of the execution main class
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
        }
        // Publish the application context startup completion event
        listeners.started(context);
        // Execute all Runner runners
        this.callRunners(context, applicationArguments);
    } catch (Throwable var10) {
        this.handleRunFailure(context, var10, exceptionReporters, listeners);
        throw new IllegalStateException(var10);
    }
    try {
        // Publish application context-ready events
        listeners.running(context);
        // Returns the application context object
        return context;
    } catch (Throwable var9) {
        this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
        throw newIllegalStateException(var9); }}Copy the code

The process,

This is the Springboot startup process, which can be divided into 18 steps. Details are as follows:

This timer is used to monitor and record the startup time of the Spring Boot application. It records the name of the current task and then starts the timer.

2. Declare the application context object and exception report collection

This procedure declares the application context object. The exception report collection is also declared to collect error information and report the cause of the error to the user.

3. Set the system attribute headless value source code as follows:

private void configureHeadlessProperty(a) {
	// Call java.awt.headless
		System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
				System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
	}
Copy the code

The system assignment

public static String setProperty(String key, String value) {
    // Determine the null operation
    checkKey(key);
    // Obtain the security administrator default null
    SecurityManager sm = getSecurityManager();
    if(sm ! =null) {
        sm.checkPermission(new PropertyPermission(key,
            SecurityConstants.PROPERTY_WRITE_ACTION));
    }
    / / return
    return (String) props.setProperty(key, value);
}
Copy the code

The purpose is to set java.awt. headless = true, where AWT (Abstract Window Toolkit) means Abstract Window toolset. Set to true to run a Headless server that can be used for some simple image processing.

4. Create all Spring run listeners and publish application startup events

This procedure is used to get the configured listener name and instantiate all classes.

5. Initialize the default application parameter class

That is, declare and create an application parameter object.

6. Prepare the environment

Create the configuration and bind the environment (through profiles such as Property Sources and Profiles).

7. Create a print class for the Banner

The Banner image is printed when Spring Boot is started

This banner information is defined in the SpringBootBanner class, and we can customize the banner information by implementing the banner interface, Then set the Spring Boot project to use your own custom Banner information using the setBanner() method, or add a Banner. TXT file under Resources to add the Banner information to this file. You can implement custom banner function.

8. Create an application context

Different ApplicationContext context objects are created for different application types.

9. Instantiate the exception reporter

It calls the getSpringFactoriesInstances () method to get the configuration exception class name, and instantiate all exception handling classes.

10. Prepare the application context

The main purpose of this method is to prepare the context by passing the created object to the prepareContext, such as binding the environment object to the context, configuring the bean generator and resource loader, and logging the startup.

11. Refresh the application context

This method is used to parse configuration files, load bean objects, and launch the built-in Web container.

12. Event handling after context refresh is applied

	/**
	 * Called after the context has been refreshed.
	 * @param context the application context
	 * @param args the application arguments
	 */
	protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {}Copy the code

The source code for this method is empty, so you can do some custom post-processing.

13. Stop the timing monitoring class

Stop the program timer in the first step of this process and count the execution information for the task.

14. Output log information

To console output related record information, such as class name, time, etc.

15. Publish the application context startup completion event

Trigger all SpringApplicationRunListener started event listener method.

16. Execute all Runner runners

Execute all ApplicationRunner and CommandLineRunner runners.

17. Publish application context-ready events

Trigger all SpringApplicationRunListener listener running events.

18. Return the application context object

At this point, the Spring Boot startup program is finished, and we can use the Spring Boot framework normally.