006 Automatic Configuration

Source: Internet
Author: User

I. Overview

One of the most popular features in Springboot is the automatic configuration. Springboot helps us to configure the entire development environment based on automatic configuration, which allows us to not have to do the repetitive configuration work every time.

In this, we will analyze the principle of automatic configuration.

Two. program start-Up class

@SpringBootApplication  Public class Springbootrunnerclass {        publicstaticvoid  main (string[] args) {        Springapplication.run (Springbootrunnerclass. class , args);}    }

In our Springboot program startup class, we used an annotation @springbootapplicatiion annotation.

Let's take a look at this note to help us accomplish something.

= {        = filtertype.custom, classes = Typeexcludefilter.  Class),        = filtertype.custom, classes = Autoconfigurationexcludefilter. class )}) public @interface springbootapplication {

We found that there are three sub-annotations on this note, so let's see what this note is for.

@Configuration  Public @interface springbootconfiguration {}

In the first annotation, we find that it is a configuration class, but it is just an annotation that Springvoot deliberately defines.

@Repeatable (Componentscans.  Class) public @interface Componentscan

The third note, we are very familiar with, that is, the package annotation, in the Springboot, the default sweep strategy is to start the package of packets to scan.

Now, all of our attention is placed on the second note.

@AutoConfigurationPackage @import (enableautoconfigurationimportselector. class ) public @interface enableautoconfiguration {

We found that there are two sub-annotations on this note. Let's see what they do.

/* * * Indicates the package containing the annotated class should is registered with * {@link autoconfigurationpack Ages}. @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented @inherited@import ( Autoconfigurationpackages.registrar. class ) public @interface autoconfigurationpackage {}

From the gaze above, we can see that it helps us register all the beans for the package.

Let's take a look at what the class that helped us introduce is used.

 Public classEnableautoconfigurationimportselector extends Autoconfigurationimportselector {@Overrideprotectedboolean isenabled (Annotationmetadata metadata) {if(GetClass (). Equals (Enableautoconfigurationimportselector.class)) {            returngetenvironment (). GetProperty (Enableautoconfiguration.enabled_override_property, Boolean.class,                    true); }        return true; }}

Let's look at its parent class:

@Override Publicstring[] Selectimports (Annotationmetadata annotationmetadata) {if(!isenabled (Annotationmetadata)) {            returnNo_imports; }        Try{autoconfigurationmetadata Autoconfigurationmetadata=autoconfigurationmetadataloader. Loadmetadata ( This. Beanclassloader); Annotationattributes attributes=getattributes (Annotationmetadata); List<String> configurations =getcandidateconfigurations (annotationmetadata, attributes); Configurations=removeduplicates (configurations); Configurations=sort (configurations, autoconfigurationmetadata); Set<String> exclusions =getexclusions (annotationmetadata, attributes);            Checkexcludedclasses (configurations, exclusions);            Configurations.removeall (exclusions); Configurations=Filter (configurations, autoconfigurationmetadata);            Fireautoconfigurationimportevents (configurations, exclusions); returnConfigurations.toarray (Newstring[configurations.size ()]); }        Catch(IOException ex) {Throw NewIllegalStateException (ex); }    }

We find that this is the @import of a component that imports beans, and what we need to focus on now is what is being imported for us?

    protected Static " meta-inf/ "            " spring-autoconfigure-metadata.properties ";

We found that a lot of beans were added to the configuration. Many of these beans are configuration classes, which basically exist under the Springboot automatic configuration package. That is, most of the beans in the configuration file under this path will be registered with our bean.

 Public Static " meta-inf/spring.factories ";

We also found that a lot of components were introduced from this configuration file.

In other words, Springboot will load a lot of beans from some of the above configuration files.

Three. Automatic Configuration class

We saw from above that springboot almost loaded all the automatic configuration classes under the Autoconfiguration package for us.

Let's see what we got underneath this bag.

All the classes inside are Auto-config classes, so let's look at a simple one.

@Configuration @conditionalonclass (Gson. class )publicclass  gsonautoconfiguration {    @Bean    @ConditionalOnMissingBean    public   Gson Gson () {        returnnew  Gson ();}    }

We found that the above is a simple configuration class, if the classpath is under a Gson class, and there are no Gson objects in the container, Springboot will help us inject a bean into the container.

Four [email protected] Annotations

In Springboot (actually introduced in Spring4), we introduced some conditional annotations that would help us determine whether or not to register beans with the container in a running environment.

is actually a Boolean judgment, if the condition is satisfied, it will be injected, otherwise it will not be injected.

Let's look at a few common annotations:

[1] Conditionalonbean: When the bean is contained within the container, it is injected

[2] Conditionalonclass: When the class path has this class, it will be registered

[3] Conditionalonproperty: When there is this attribute in the environment variable, it is registered

And so on, Springboot is the automatic assembly done by these annotations.

Five. Analysis of automatic Assembly

We use a relatively simple configuration class for automatic configuration of the general process of analysis:

@Configuration @enableconfigurationproperties (httpencodingproperties.class) @ConditionalOnWebApplication @conditionalonclass (characterencodingfilter.class) @ConditionalOnProperty (prefix="spring.http.encoding", value ="enabled", matchifmissing =true) Public classhttpencodingautoconfiguration {Privatefinal Httpencodingproperties properties;  Publichttpencodingautoconfiguration (httpencodingproperties properties) { This. Properties =properties; } @Bean @ConditionalOnMissingBean (characterencodingfilter.class)     PublicCharacterencodingfilter Characterencodingfilter () {characterencodingfilter filter=NewOrderedcharacterencodingfilter (); Filter.setencoding ( This. Properties.getcharset (). name ()); Filter.setforcerequestencoding ( This. Properties.shouldforce (type.request)); Filter.setforceresponseencoding ( This. Properties.shouldforce (Type.response)); returnfilter; } @Bean PublicLocalecharsetmappingscustomizer Localecharsetmappingscustomizer () {return NewLocalecharsetmappingscustomizer ( This. Properties); }    Private Static classLocalecharsetmappingscustomizer implements Embeddedservletcontainercustomizer, Ordered {Privatefinal Httpencodingproperties properties; Localecharsetmappingscustomizer (Httpencodingproperties properties) { This. Properties =properties; } @Override Public voidCustomize (Configurableembeddedservletcontainer container) {if( This. properties.getmapping ()! =NULL) {container.setlocalecharsetmappings ( This. properties.getmapping ()); }} @Override Public intGetOrder () {return 0; }    }}

[1] First, we found this to be a configuration class.

[2] @ConditionalOnWebApplication indicates the need to register in a Web environment

[3] @ConditionalOnClass (Characterencodingfilter.class) indicates that a class needs to be registered under the Classpath

[4] @ConditionalOnProperty (prefix = "spring.http.encoding", value = "Enabled", Matchifmissing = True) This indicates that this property is available under the configuration file , but the default value is given here, which means it must be true, unless the user actively cancels the configuration.

[5] @EnableConfigurationProperties (httpencodingproperties.class) This annotation indicates completion of the Httpencodingproperties property of this property configuration class to populate.

Here, let's analyze the source code:

    Private final httpencodingproperties properties;      Public httpencodingautoconfiguration (httpencodingproperties properties) {        this. Properties=  properties;    }

We see from the above annotations that a Httpencodingproperties class is registered with the container, and the automatic configuration class is instantiated. That is, the properties of the Httpencodingproperties are now populated.

@Bean @ConditionalOnMissingBean (characterencodingfilter.class)     PublicCharacterencodingfilter Characterencodingfilter () {characterencodingfilter filter=NewOrderedcharacterencodingfilter (); Filter.setencoding ( This. Properties.getcharset (). name ()); Filter.setforcerequestencoding ( This. Properties.shouldforce (type.request)); Filter.setforceresponseencoding ( This. Properties.shouldforce (Type.response)); returnfilter; }

Represents adding a character encoding filter to a container.

@Bean      Public Localecharsetmappingscustomizer Localecharsetmappingscustomizer () {        returnnew Localecharsetmappingscustomizer (this. properties);    }

Represents adding a custom configurator to the container.

Six. Basic process of automatic configuration

[1] A property configuration class is typically bound to a property file

[2] This property is then populated with the properties of the auto-configuration Class I

[3] Then is the creation of different beans into the container, until the completion of the entire Springboot automatic configuration.

Seven. Automatic Configuration Report

We now know the principle of automatic configuration of springvoot, but we see that the automatic configuration is very complex, how can we be sure that a bean has been initialized well?

Springboot provides us with an automatic configuration report.

Debug=True

In the main configuration file, we can add the configuration as above, and then start the springboot when the automatic configuration report generation is turned on.

Different configuration report information is displayed on our console.

What is shown here is the bean that springboot helps us add, which is the class that automatically configures the success.

The following shows a class that has no automatic success.

006 Automatic Configuration

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.