Location>code7788 >text

An article thoroughly understand the Spring Boot startup process

Popularity:422 ℃/2024-11-08 22:17:02

I. Spring Boot startup process

1. Launching the portal

The startup entry point for a Spring Boot application is usually a file containing the@SpringBootApplication annotation to the main class and call the() Methods.@SpringBootApplication is a compound annotation that contains the@Configuration@EnableAutoConfiguration cap (a poem)@ComponentScan, thereby turning on auto-configuration and component scanning.

The source code path is in theSpringApplication classrun() Methods:

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return new SpringApplication(primarySource).run(args);
}

This portal does the following main things:

  1. Creating a SpringApplication Instance: Initialize the Spring Boot environment.
  2. Initializing the Environment and Listeners: Setting up the startup of theEnvironmentand addApplicationListener Listener.
  3. Preparing and Refreshing Spring Contexts: ByprepareContext cap (a poem)refreshContext method performs context preparation and refreshing.

2. Create a SpringApplication instance

existSpringApplication method, Spring Boot resolves the startup mode of the application (e.g., whether it's a web application, a servlet application, or a regular application) and initializes the application's context type.Spring Boot's different context types includeAnnotationConfigApplicationContext(non-Web applications) andAnnotationConfigServletWebServerApplicationContext(Web application).

3. Initialize Environment and listeners

Next, Spring Boot initializes theConfigurableEnvironmentThis environment contains system properties, environment variables, configuration files, and other data that serve as the basis for subsequent loading of bean definitions and initialization.

At the same time, Spring Boot initializes a series ofApplicationListener, which is used to listen for and handle events during the application startup process, such as theApplicationEnvironmentPreparedEventApplicationPreparedEvent etc.

4. Loading configuration classes and triggering auto-configuration

Spring Boot Usage@EnableAutoConfiguration annotation triggers autoconfiguration, the core implementation is in theAutoConfigurationImportSelector LoadingMETA-INF/ configuration file, which lists a number of autoconfiguration classes (such as theDataSourceAutoConfigurationJpaRepositoriesAutoConfiguration etc.) and loads the appropriate autoconfiguration based on conditions (e.g., whether certain beans exist, whether certain properties are configured, etc.).

5. Load and register the bean

existrefreshContext() method, Spring Boot calls therefresh() method, this step completes the initialization of the BeanFactory and theBeanPostProcessor registration, and parses the@Component@Service@Repository and other annotated bean definitions, registering them with theBeanFactory Center.

At the source code level.refresh() method.invokeBeanFactoryPostProcessors cap (a poem)registerBeanPostProcessors These two methods are key and are each used to execute all theBeanFactoryPostProcessor respond in singingBeanPostProcessorThe Bean's lifecycle is managed correctly by the Bean's user interface, which is a key component of the Bean's lifecycle.

6. Embedded container startup in Web environments

In a web application, Spring Boot launches an embedded web container (such as Tomcat or Jetty).Spring Boot launches an embedded web container by default through theServletWebServerApplicationContext Start the embedded web server. In therefresh() At the end of the process, the embedded container is launched and the application is published as a web application.

7. Execution of ApplicationRunner and CommandLineRunner

After Spring Boot finishes launching, it scans and executes all of the files that have implemented theApplicationRunner cap (a poem)CommandLineRunner They can be used to execute custom logic after startup.

8. Publish the application launch completion event

Finally, Spring Boot releasesApplicationReadyEvent event to notify all listeners that the application has finished starting. At this point, the Spring Boot application is officially started and can receive HTTP requests or perform other tasks.

Second, the Spring Boot startup process of architectural design

During Spring Boot application startup, the() is the most commonly used startup method. Through this method, Spring Boot for developers to shield a lot of complex initialization details, we only need to provide the main startup class entry and simple configuration information can start the entire application.

Let's start with the source code and analyze it step by step Operations performed.

1, () of the detailed process

The following major steps are accomplished:

  1. Initializing a SpringApplication Instance

    This instance is responsible for the entire Spring Boot application startup process, by determining the application type and setting environment variables to provide the basis for subsequent configuration loading and application context creation. The core methods areSpringApplication#prepareEnvironment cap (a poem)SpringApplication#createApplicationContext

  2. Creating an application context and refreshing it

    SpringApplication will be created differently depending on the type of applicationApplicationContext(e.g.AnnotationConfigApplicationContext maybeServletWebServerApplicationContext), and all of theBean Load into context.

  3. Loading Environment Configuration

    Spring Boot loads different configuration files based on the development or production environment. The core isConfigFileApplicationListener Listens for configuration events and parses the application configuration file ( maybe) and assembled into the application context of theEnvironment in the object.

  4. Starting Embedded Containers

    In the case of a web application, Spring Boot starts the embedded server (such as Tomcat, Jetty, or Undertow) and sends theDispatcherServlet Register to the server.

2, SpringApplication core design class

At the source code level.SpringApplication is the key class in the startup process. It is called via the constructor and therun() The method accomplishes the following:

public class SpringApplication {

    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
         = resourceLoader;
        (primarySources, "PrimarySources must not be null");
         = new LinkedHashSet<>((primarySources));
         = deduceWebApplicationType();
        ((Collection) getSpringFactoriesInstances(
            ));
        ((Collection) getSpringFactoriesInstances());
         = deduceMainApplicationClass();
    }

    public ConfigurableApplicationContext run(String... args) {
        // initialization phase
        StopWatch stopWatch = new StopWatch();
        ();
        ConfigurableApplicationContext context = null;
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        ();
        
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            context = createApplicationContext();
            prepareContext(context, environment, listeners, applicationArguments);
            refreshContext(context);
            afterRefresh(context, applicationArguments);
            (context);
            callRunners(context, applicationArguments);
        } catch (Exception ex) {
            handleRunFailure(context, listeners, ex);
            throw new IllegalStateException(ex);
        } finally {
            ();
        }
        return context;
    }
}

The source code reveals theSpringApplication The core functionality lies in several areas such as configuring listeners, loading environments, and creating contexts. This is accomplished through thededuceWebApplicationType() method determines the type of web application for the nextApplicationContext The selection provides the basis. This design enables a high degree of customization and flexible adaptation of the start-up process.


III. Key components and design patterns in the start-up process

Spring Boot's startup process involves several design patterns that not only improve code readability and flexibility, but also ensure that startup behavior can be quickly adapted in different business scenarios.

1, ApplicationContext and ConfigurableEnvironment

ApplicationContext is one of the core concepts of the Spring framework, providing an implementation of the IoC container and management of the application context. In Spring Boot, theApplicationContext contains all the beans and provides an interface between the application and the external environment, such as theConfigurableEnvironment, which is used to manage the application's environment configuration and properties.

Core Design of ApplicationContext

ApplicationContext is a highly abstract interface with multiple concrete implementations such asAnnotationConfigApplicationContext cap (a poem)ServletWebServerApplicationContextSpring Boot'sSpringApplication Will choose the right one depending on the type of applicationApplicationContext implementations, and configure and initialize them:

  • Non-Web applications: useAnnotationConfigApplicationContext Load configuration classes and beans.
  • Web applications: usingServletWebServerApplicationContextand loads the embedded Web container configuration.

This design pattern enhances theApplicationContext The adaptability of the product allows it to be flexibly adapted to a wide range of different types of applications.

ConfigurableEnvironment Loading of the environment configuration

ConfigurableEnvironment Provides information about the application's environment, including system properties, environment variables, and externalized configuration file contents. During the Spring Boot startup process, theConfigurableEnvironment will be inprepareEnvironment() method is initialized.

existConfigurableEnvironment The prioritization of attribute sources greatly enhances configuration flexibility.Spring Boot prioritizes attribute sources based on the differentPropertySource(e.g.The system also provides priority management (e.g., environment variables, command line arguments, etc.), which makes it possible to flexibly override configurations even in complex environments.

2, ApplicationListener event-driven model

ApplicationListener is an implementation of the event-driven mechanism in the Spring Framework, which Spring Boot uses to manage all kinds of important events during the boot process. The following are common startup events:

  • ApplicationStartingEvent: in() Triggered at the beginning.
  • ApplicationEnvironmentPreparedEvent: inEnvironment Trigger when ready.
  • ApplicationPreparedEvent: Triggered before the context is loaded.
  • ApplicationStartedEvent: Triggered after the context refresh is complete.
  • ApplicationReadyEvent: Triggered when the application startup completes.

The event-driven model allows developers to customize actions at various stages of application startup, greatly enhancing scalability and flexibility.

3, Dependency injection and conditional configuration loading mechanism

Autoconfiguration in Spring Boot relies on the conditional loading mechanism, which centers around the@Conditional series of annotations, such as@ConditionalOnClass cap (a poem)@ConditionalOnMissingBean etc. These annotations allow Spring Boot to selectively load configurations as appropriate:

@Configuration
@ConditionalOnClass()
public class DataSourceAutoConfiguration {
    // Data source auto-configuration logic
}

This conditional injection pattern reduces wasted resources by loading beans on demand. This design pattern also allows Spring Boot to quickly adapt to different environments and dependency scenarios, avoiding the loading of unnecessary beans.


IV. Mechanisms for realizing auto-configuration

Spring Boot is available through the@EnableAutoConfiguration Start the autoconfiguration feature, which is implemented underneath the mechanism of theAutoConfigurationImportSelector cap (a poem)SpringFactoriesLoaderwhichSpringFactoriesLoader scanningMETA-INF/ File loading autoconfiguration classes.

1, SpringFactoriesLoader Detailed

A core mechanism of Spring Boot autoconfiguration is theSpringFactoriesLoaderIt's going to come out of theMETA-INF/ file to load all the classes that need to be autoconfigured. This approach to file configuration makes it easy for Spring Boot to extend new autoconfiguration features.

@EnableAutoConfiguration pass (a bill or inspection etc)AutoConfigurationImportSelector to load the autoconfiguration classes, and the autoconfiguration implementation classes and logic are used by the@Conditional annotation management, which makes autoconfiguration on-demand loadable.

2, conditional annotations and scenario applications

The auto-configuration mechanism is widely used in real business. For example, the configuration of data sources in Spring Boot is done through theDataSourceAutoConfiguration class implementation. In theDataSourceAutoConfiguration In the@ConditionalOnClass annotation to determine the presence of theDataSource class, if present, injects the data source configuration.

This type of scenario is ideal for use with multiple data source configurations. Developers can utilize conditional annotations to configure multiple database sources in production environments, while only loading test data source configurations in test environments.


V. Embedded container startup process

Spring Boot uses embedded containers by default in web applications, which allows applications to run independently of external servers, improving application independence and convenience.

1, Embedded container startup design

When Spring Boot launches a web application, it starts the web application according to theServletWebServerApplicationContext Load the embedded container. The following is the key process for starting an embedded container:

  1. Create ServletWebServerApplicationContext: Spring Boot selects the context class for the web application.ServletWebServerApplicationContextand loadWebServerFactory Factory class.
  2. Creating a Web Server: Spring Boot uses factory classes to create embedded web servers such as Tomcat, Jetty, or Undertow.
  3. Register DispatcherServlet: Spring Boot willDispatcherServlet registers to the embedded server with theServletRegistrationBean Initialize and configure it.

This design pattern allows Spring Boot applications to seamlessly support different types of Web containers and to flexibly choose the right container for the environment.

2, Embedded containers in multiple environments

Embedded containers are particularly well suited for microservices architectures, which can quickly adapt to deployment platforms such as Docker or Kubernetes in containerization scenarios. In addition, Spring Boot allows developers to switch between different types of web servers (e.g., Tomcat to Jetty) through simple configuration, which is designed to provide high flexibility for enterprise applications.