"Go" Spring Boot Dry series: (iii) Starting principle analysis

Source: Internet
Author: User
Tags class definition instance method

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

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

As can be seen from the above code, annotation definition ( @SpringBootApplication ) and class definition (Springapplication.run) is the most dazzling, so to uncover the springboot of the mystery, we have to start from these two bits.

The secret behind the Springbootapplication
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = {        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })public @interface 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点开查看发现里面还是应用了@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:

@Configuration@EnableAutoConfiguration@ComponentScanpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

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

@Configuration

@ConfigurationIt is not strange for us here, it is the Javaconfig form of the spring IOC container configuration class used @Configuration , the Springboot community recommended the use of Javaconfig-based configuration, so, here the startup class labeled @Configuration After that, it is actually a configuration class for the IOC container.
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:

    <?xml version="1.0" encoding="UTF-8"?>    <beans xmlns="http://www.springframework.org/schema/beans"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"           default-lazy-init="true">        <!--bean定义-->    </beans>

The Javaconfig-based configuration is as follows:

@Configurationpublic class MockConfiguration{    //bean定义}

Any one @Configuration of the annotated Java class definitions is a Javaconfig configuration class.

Registering the bean definition plane
The form of XML-based configuration is this:

<bean id="mockService" class="..MockServiceImpl">    ...</bean>

The configuration form based on Javaconfig is this:

@Configurationpublic class MockConfiguration{    @Bean    public MockService mockService(){        return new MockServiceImpl();    }}

Any annotated @Bean method whose return value is registered as a bean definition to the spring IOC container, the method name defaults to the bean's defined ID.

Expression Dependency Injection Relationship level
In order to express the dependency between beans and beans, this is generally the case in XML form:

<bean id="mockService" class="..MockServiceImpl">    <propery name ="dependencyService" ref="dependencyService" /></bean><bean id="dependencyService" class="DependencyServiceImpl"></bean>

The configuration form based on Javaconfig is this:

@Configurationpublic class MockConfiguration{    @Bean    public MockService mockService(){        return new MockServiceImpl(dependencyService());    }        @Bean    public DependencyService dependencyService(){        return new DependencyServiceImpl();    }}

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

@ComponentScanThis annotation is important in spring, which corresponds to the elements in the XML configuration, which @ComponentScan is the ability to automatically scan and load eligible components (such as @Component and @Repository so on) or bean definitions, and eventually load those bean definitions into the IOC container.

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

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

@EnableAutoConfiguration

Personally feel @EnableAutoConfiguration this annotation is the most important, so put in the last to interpret, do you remember the Spring Framework provides a variety of names @Enable beginning with the annotation definition? For example,, and @EnableScheduling @EnableCaching so on @EnableMBeanExport , @EnableAutoConfiguration the idea and way of doing things in fact same strain, a simple summary is that, with @Import the support of the collection and registration of specific scenarios related to the bean definition.

@EnableSchedulingis by @Import loading the bean definitions associated with the spring dispatch framework into the IOC container.
@EnableMBeanExportis by @Import loading the JMX-related bean definitions into the IOC container.
And @EnableAutoConfiguration It's also @Import the help that loads all the bean definitions that meet the automatic configuration criteria into the IOC container, that's all!

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

@SuppressWarnings("deprecation")@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import(EnableAutoConfigurationImportSelector.class)public @interface EnableAutoConfiguration {    ...}

The most critical of these is @Import(EnableAutoConfigurationImportSelector.class) that, with Enableautoconfigurationimportselector, @EnableAutoConfiguration you can help the Springboot application to apply all eligible @Configuration The configuration is loaded 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 tools of the Spring Framework: Springfactoriesloader support, @EnableAutoConfiguration Intelligent automatic configuration can be 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.

public abstract class SpringFactoriesLoader {    //...    public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {        ...    }    public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {        ....    }}

In conjunction @EnableAutoConfiguration with it, it is more of a feature support for configuration lookups, which is based on @EnableAutoConfiguration The full class name org.springframework.boot.autoconfigure.EnableAutoConfiguration as the lookup key to 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, the @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 annotated @Configuration的JavaConfig form of the IOC container configuration class, 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:

    • 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.

  • Once the Springapplication instance is initialized and the settings are complete, the logic of the Run method starts, and the method executes at the beginning of the execution. 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!" ”。

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

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

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

  • 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 app 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.

  • Once 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.

  • Iterates through the contextprepared () method that calls all Springapplicationrunlistener.

  • The core step is to @EnableAutoConfiguration load all previously acquired configuration and other forms of IOC container configuration into the ready-made applicationcontext.

  • Iterates through the contextloaded () method that calls all Springapplicationrunlistener.

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

  • Finds whether Commandlinerunner are registered in the current applicationcontext, and if so, the traversal executes them.

  • Normally, traversing the finished () method that executes Springapplicationrunlistener (if an exception occurs throughout the process, all Springapplicationrunlistener finished () are still called method, except that the exception information is passed into the processing in this case)
    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.

To see more spring boot dry tutorials, go to: Spring Boot Dry Series Master

Reference

Most of the chapters in this chapter refer to the third chapter of the book "Springboot Quick Build as a service system", which is the most thorough chapter of the book, which is the most essential part of the book. So I didn't hold back and share it for everyone to learn. Of course, I do not have the electronic version of this book, can not share to everyone, deeply regret (.? _?). )?

"Go" Spring Boot Dry series: (iii) Starting principle analysis

Related Article

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.