Spring Boot Dry series: (iii) Start-up principle analysis

Source: Internet
Author: User
Tags class definition instance method

This article turns from http://www.cnblogs.com/zheting/p/6707035.html thanks to the author Spring Boot Dry series: (iii) Starting principle analysis2017-03-13 toot md du ye Java Super Theological hall

Objective

In the first few chapters we have seen the springboot for us to do automatic configuration, indeed convenient and fast, but for beginners, if not understand springboot internal starting principle, will inevitably suffer. So this time the blogger will be with you step by step to uncover the mystery of springboot, let it not mysterious.

Body

If we develop any spring boot project, we will use the following startup class

As you can see from the code above, Annotation definitions (@SpringBootApplication) and class definitions (Springapplication.run) are the most dazzling, so to uncover Springboot's mystery, we will start with these two.

The secret behind the Springbootapplication

Although the definition uses more than one annotation to label the original information, it is actually important to have only three annotation:

    • @Configuration (@SpringBootConfiguration point of view found inside or applied @configuration)

    • @EnableAutoConfiguration

    • @ComponentScan

So, if we use the following Springboot startup class, the entire Springboot application can still be equivalent to the previous startup class function:

Each time write these 3 more tired, so write a @springbootapplication convenient point. Next, we introduce the 3 annotation respectively.

@Configuration

The @configuration here is not strange to us, it is the Javaconfig form of the spring IOC container configuration class used by the @configuration,springboot community recommend the use of Javaconfig-based configuration form , so, after the startup class here has labeled @configuration, it is actually a configuration class for the IOC container itself.

For a few simple examples, the difference between XML and config configuration is as follows:

    • form level of expression

      This is how the XML configuration is based:

The Javaconfig-based configuration is as follows:

Any Java class definition labeled @configuration is a Javaconfig configuration class.

    • Registering the bean definition plane

      The form of XML-based configuration is this:

The configuration form based on Javaconfig is this:

Any method that labels the @bean, whose return value is registered as a bean definition to the Spring IOC container, defaults to the ID of the bean definition.

    • Expression Dependency Injection Relationship level

      In order to express the dependency between beans and beans, this is generally the case in XML form:

The configuration form based on Javaconfig is this:

If the definition of a bean relies on other beans, it is possible to call directly the creation method of the dependent bean in the corresponding Javaconfig class.

@ComponentScan

@ComponentScan This annotation is important in spring, it corresponds to the element in the XML configuration, @ The function of Componentscan is to automatically scan and load eligible components (such as @component and @repository, etc.) or bean definitions, and eventually load these bean definitions into the IOC container.

We can use properties such as basepackages to fine-grained custom @componentscan the scope of automatic scanning, and if not specified, the default spring framework implementation will be scanned from the package of the class where the declaration @componentscan is located.

Note: So Springboot's startup class is best placed under the root package because Basepackages is not specified by default.

@EnableAutoConfiguration

Personal feeling @enableautoconfiguration This annotation is the most important, so at the end of the interpretation, do you remember the Spring Framework provides a variety of names @enable the beginning of the annotation definition? such as @enablescheduling, @EnableCaching, @EnableMBeanExport, and so on, @EnableAutoConfiguration philosophy and way of doing things in fact same strain, a simple summary is that, Collect and register specific scenario-related bean definitions with @import support.

    • The @EnableScheduling is to load the bean definitions associated with the spring dispatch framework into the IOC container through @import.

    • The @EnableMBeanExport is to load the JMX-related bean definitions into the IOC container via @import.

@enableautoconfiguration is also using @import's help to load all the bean definitions that meet the automatic configuration criteria into the IOC container, that's all!

@EnableAutoConfiguration as a composite annotation, its own definition of key information is as follows:

Among them, the most critical is @import (Enableautoconfigurationimportselector.class), with the help of enableautoconfigurationimportselector,@ Enableautoconfiguration can help the Springboot app load all eligible @configuration configurations into the IOC container that is created and used by the current springboot. It's like a "octopus".

With the help of one of the original tool classes in the Spring framework: Springfactoriesloader support, @EnableAutoConfiguration can intelligently configure the power to get it done!

Auto-Configure behind the scenes Heroes: Springfactoriesloader detailed

Springfactoriesloader is an extension scheme that is private to the spring framework, and its primary function is to load the configuration from the specified configuration file meta-inf/spring.factories.

With @enableautoconfiguration, it is more of a feature support for configuration lookups, That is, according to @enableautoconfiguration's full class name org.springframework.boot.autoconfigure.EnableAutoConfiguration as the key to find, Get a corresponding set of @configuration classes

is a piece of content that is excerpted from the Meta-inf/spring.factories configuration file in the Springboot autoconfigure dependency package, which can be a good illustration of the problem.

So, @EnableAutoConfiguration automatically configured Magic Knight becomes: Search all the meta-inf/from the Classpath Spring.factories the configuration file and org.springframework.boot.autoconfigure.EnableutoConfiguration the corresponding configuration item through the Reflection (Java Refletion) is instantiated into the corresponding IOC container configuration class labeled @configuration in javaconfig form, then summarized as one and loaded into the IOC container.

Explore the springapplication execution process in depth

The implementation of the Springapplication run method is the main line of our journey, the main process of this method can be summarized as follows:

1) If we are using the static Run method of Springapplication, this method first creates an instance of the Springapplication object, and then invokes the instance method of the created springapplication. When the Springapplication instance is initialized, it does a few things in advance:

    • Depending on whether there is a feature class (Org.springframework.web.context.ConfigurableWebApplicationContext) inside the classpath, decide if you should create a applicationc to use for your web App The Ontext type.

    • Use Springfactoriesloader to find and load all available Applicationcontextinitializer in the app's classpath.

    • Use Springfactoriesloader to find and load all available Applicationlistener in the app's classpath.

    • Infers and sets the definition class for the main method.

2) After the initialization of the Springapplication instance is complete and the setup is complete, the logic of the Run method is started, and the method is executed at the beginning. The first traversal performs all the springapplicationrunlistener that can be found and loaded through Springfactoriesloader. Call their started () method and tell these springapplicationrunlistener, "Hey, springboot app is going to start executing!" ”。

3) Create and configure the environment that will be used by the current spring boot app (including configuring the Propertysource and profile to be used).

4) Iterate through the methods that call all Springapplicationrunlistener's environmentprepared () and tell them: "The environment currently used by the Springboot application are ready!" ”。

5) If the Springapplication Showbanner property is set to True, the banner is printed.

6) Depending on whether the user has explicitly set the Applicationcontextclass type and the inferred results of the initialization phase, decide what type of ApplicationContext to create for the current Springboot application and create the completion, Then, depending on the criteria, decide whether to add Shutdownhook, decide whether to use a custom beannamegenerator, decide whether to use a custom resourceloader, and, of course, the most important, Set up the previously prepared environment to be used by the created ApplicationContext.

7) Once the ApplicationContext is created, Springapplication will again use Spring-factoriesloader, Find and load all the available applicationcontext-initializer in Classpath, The Initialize (ApplicationContext) method that calls these applicationcontextinitializer is then traversed to further process the applicationcontext that have been created.

8) Iterate through the contextprepared () method that calls all Springapplicationrunlistener.

9) The core step is to load all previously acquired configuration and other forms of the IOC container configuration into the prepared applicationcontext.

10) Iterate through the contextloaded () method that calls all Springapplicationrunlistener.

11) Call ApplicationContext's Refresh () method to complete the last operation available for the IOC container.

12) Find whether there are commandlinerunner registered in the current applicationcontext, and if so, traverse to execute them.

13) Normally, traverse the finished () method that executes Springapplicationrunlistener (if the whole process is an exception, All Springapplicationrunlistener's finished () methods are still called, except in this case the exception information is passed into the processing.

After the event notification point is removed, the entire process is as follows:

Summarize

To this, Springboot's core components have completed the basic analysis, in general, most of the spring framework behind some of the concepts and practices, springboot only in these concepts and practices in advance to the specific scene of curing and sublimation, And it is precisely these cures that allow us to develop applications based on the sping framework to be more convenient and efficient.

Spring Boot Dry series: (iii) Start-up principle analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.