Spring boot 2.0.6 starts the parsing startup process

Keywords: Programming Spring Java Attribute Mybatis

Analysis of the run method of spring application

public ConfigurableApplicationContext run(String... args) {
    // Construct a task execution observer (Java class for viewing time and performance)
   StopWatch stopWatch = new StopWatch();
    // Start execution, record start time
   stopWatch.start();
    // Custom configuration context, top-level parent class contains Bean Factory
   ConfigurableApplicationContext context = null;
    // Define a collection of errors (to support reporting errors about startup)
   Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    //Define a headless of AWT (set the headless mode, and set the system property with the name of java.awt.headless to true)
   configureHeadlessProperty();
    // Get a run listener, mainly listening to the SpringApplication object. (there is only one eventpublishingrunnlistener inside)
   SpringApplicationRunListeners listeners = getRunListeners(args);
    //Call the start of listener, when the run method of SpringApplication object is just started (relying on SimpleApplicationEventMulticaster)
   listeners.starting();
   try {
        // Construct an application parameter holding class to apply parameterization
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);      
        //Create and configure the Environment (the process will get the input parameters and load the application configuration file), and add the Environment to the listener object (SpringApplicationRunListeners)
      ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
      // Configure the ignored information of the bean to scan print.beaninfo.ignore for attribute reading optional true/false (configured in the application file)
      configureIgnoreBeanInfo(environment);
     //Print the logo, that is, the beaninfo.ignore sample of the printboot
      Banner printedBanner = printBanner(environment);
      // Create the corresponding Context container initialization bean according to the application type***
      context = createApplicationContext();
       // Get the specific implementation class from the configuration file
      exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
            new Class[] { ConfigurableApplicationContext.class }, context);
      // Ready to use Context before refreshing Context
      // Associate important component rain context objects such as SpringApplicationRunListeners, ConfigurableEnvironment, ApplicationArguments, Banner, etc.
      prepareContext(context, environment, listeners, applicationArguments,
            printedBanner);
      // Refresh Context container***
      // The key to realize the automatic configuration of spring boot starter - * (mybatis, redis, etc.), including the core work of spring.factories loading, bean instantiation, etc.
      refreshContext(context);
      // Process after refreshing the Context container
      afterRefresh(context, applicationArguments);
        // End of execution, record execution time
      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass)
               .logStarted(getApplicationLog(), stopWatch);
      }
        // After the Context container is refreshed and published, the listener accepting the ApplicationStartedEvent event will perform the corresponding operation.
        //[the spring container has been refreshed and the application has been started, but CommandLineRunners and ApplicationRunners haven't been called yet. They are sent directly through the spring container itself.
        // (because ApplicationListener has been added to the spring container)
      listeners.started(context);
        // The execution wake-up running thread after the Context container refresh is triggered
      callRunners(context, applicationArguments);
   } catch (Throwable ex) {
         // Start error report processing
      handleRunFailure(context, ex, exceptionReporters, listeners);
      throw new IllegalStateException(ex);
   }
   try {
       // After the Context is started, the Runner runs and forces the release. The listener accepting the ApplicationStartedEvent event will perform the corresponding operation.
       //[CommandLineRunners has been called and sent directly through the spring container itself (because ApplicationListener has joined the spring container)].
      listeners.running(context);
   } catch (Throwable ex) {
        // Start error report processing
      handleRunFailure(context, ex, exceptionReporters, null);
      throw new IllegalStateException(ex);
   }
    // Return to Spring container
   return context;
}

The returned object ConfigurableApplicationContext is a subclass of applicationContext. The former provides more functions than the latter. For example, it implements the lifecycle and closeable interface to better manage the declaration cycle of beans. There are other additional functions such as addBeanFactoryPostProcessor,setParent,setId,addApplicationListener,addProtocolResolver, etc.

  1. Create and launch the viewer

  2. Set the java.awt.headless system variable

  3. Load the SpringApplicationRunListener in META-INF/spring.factories under all Classpaths

  4. Call the starting method of SpringApplicationRunListener in turn, and publish the springboot start event.

  5. Instantiate ApplicationArguments object to get application parameters

  6. Create ConfigurableEnvironment object environment

    Note that webApplicationType controls the type of Environment object created. When it is SERVLET, it is StandardServletEnvironment.class, when it is inactive, it is StandardReactiveWebEnvironment.class, and the rest is StandardEnvironment.class.
  7. To configure the environment object, mainly configure the method parameters into the environment -- set properties through configurePropertySources(environment, args) and profiles through configureProfiles(environment, args)

  8. Execute the environmentPrepared method of all SpringApplicationRunListener to publish the environmentPrepared event, that is, call the onApplicationEvent event event of ApplicationListener.

  9. Binding the current environment with the current springApplication

  10. Put the ConfigurationPropertySource in the first one in the environment's propertysource

  11. Print Banner

  12. Create Spring container

  13. Get the specific exception implementation class from the configuration file

  14. Setting up the spring container's environment

  15. Set beanNameGenerator and resourceLoader

  16. Call back the initialize method of ApplicationContextInitializer to initialize the context, and check whether each ApplicationContextInitializer accepts the container of this type.

  17. Execute the contextPrepared method of all SpringApplicationRunListener, but it is currently an empty implementation

  18. Register the two bean s spring application arguments and spring bootbanner respectively

  19. Get our primarySources and sources and load them into Context

  20. To execute all SpringApplicationRunListener's contextLoaded methods, first determine whether ApplicationListener belongs to ApplicationContextAware, if so, assign the spring container to the listener, assign the ApplicationListener to spring container, and then use onApplicationEvent method of ApplicationListener.

  21. Call the refresh method of AbstractApplicationContext to refresh the Spring container

    Set some initial operations (start activation, start date, initialization propertySource), configure the standard context characteristics of the factory, register BeanPostProcessor and beanFactory postprocessor (the former implements setting before and after bean initialization, and later implements modifying beanFactory or modifying beanDefinition or adding or initializing B that is eager to initialize in advance EAN), initialization of internationalization files, initialization of web containers, instantiation of non lazy loaded remaining beans, etc.
  22. Call the registerShutdownHook method of AbstractApplicationContext to register a thread that points primarily to the doclose method

  23. Execute the started method of all springapplicationrunlisteners and publish the started event.

  24. Call back the callrunners method to get the ApplicationRunner and CommandLineRunner objects from the spring container, and then sort them in order, and call their run methods in cycles

  25. Execute the running method of all springapplicationrunlisteners and publish the running event

  26. Step 5 to step 25: call handlernfailure method to handle different abnormal state exceptions, call listeners.failed(context, exception), and close the spring container.

Posted by ashishag67 on Tue, 15 Oct 2019 23:52:29 -0700