1, the principle of automatic configuration:
1), Springboot boot time load the main configuration class, turn on the automatic configuration function [email protected]==
2), @EnableAutoConfiguration role:
Use Enableautoconfigurationimportselector to import some components into a container?
You can view the contents of the Selectimports () method;
List<String> configurations = getcandidateconfigurations (annotationmetadata, attributes); get candidate configuration
springfactoriesloader.loadfactorynames () scan all jar package Classpath META-inf/ Spring.factories wraps the contents of the scanned files into a Properties object from the properties to the values of the Enableautoconfiguration.class class (class name), and then adds them to the container
Add the values of all enableautoconfiguration that are configured within the CLASSPATH to the container meta-inf/spring.factories
# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=Org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration, Org.springframework.boot.autoconfigure.aop.AopAutoConfiguration, Org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration, Org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration, Org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, Org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration, Org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration, Org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration, Org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, Org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration, Org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, Org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration, Org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguratiOn,org.springframework.boot.autoconfigure.data.cassandra.cassandrarepositoriesautoconfiguration, Org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, Org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration, Org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration, Org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration, Org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, Org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.datA.neo4j.neo4jdataautoconfiguration, Org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, Org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, Org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration, Org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, Org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration, Org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, Org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, Org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration, Org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, Org.springframework.boot.autoconfigure.hazelcast.hazelcastautoconfiguration,org.springframework.boot.autoconFigure.hazelcast.HazelcastJpaDependencyAutoConfiguration, Org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration, Org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration, Org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, Org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, Org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, Org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration, Org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration, Org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, Org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration, Org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration, Org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration, Org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration, Org.springframework.boot.autoconfigure.jms.aRtemis. Artemisautoconfiguration,org.springframework.boot.autoconfigure.flyway.flywayautoconfiguration, Org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, Org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration, Org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration, Org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration, Org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration, Org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration, Org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, Org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration, Org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration, Org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration, Org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration, Org.springframework.boot.autoconfigure.mobile.SitePreferencEautoconfiguration,org.springframework.boot.autoconfigure.mongo.embedded.embeddedmongoautoconfiguration, Org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, Org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, Org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, Org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration, Org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration, Org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration, Org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration, Org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration, Org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration, Org.springframework.boot.autoconfigure.session.SessionAutoConfiguration, Org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration, Org.springframework.boot.autoconfigure.social.FacebookAutoConfiguratIon,org.springframework.boot.autoconfigure.social.linkedinautoconfiguration, Org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration, Org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration, Org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, Org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, Org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration, Org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, Org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration, Org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration, Org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration, Org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration, Org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration, Org.springframework.boot.autoconfigure.web.multipartautoconfiguration,org.springframework.Boot.autoconfigure.web.ServerPropertiesAutoConfiguration, Org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration, Org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration, Org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration, Org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration, Org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
Each such xxxautoconfiguration class is a component in the container, which is added to the container; they are used for automatic configuration;
3), each automatic configuration class for automatic configuration function;
4), with httpencodingautoconfiguration (HTTP encoding automatic configuration) as an example to explain the principle of automatic configuration;
@Configuration//indicates that this is a configuration class, like a previously written configuration file, or you can add components to a container@EnableConfigurationProperties (httpencodingproperties.class)//starts the Configurationproperties function of the specified class, binds the corresponding value in the configuration file to the Httpencodingproperties, and adds the httpencodingproperties to the IOC container @ConditionalOnWebApplication//Spring Bottom @conditional annotations (Spring annotated version), depending on the conditions, if the specified conditions are met, the configuration within the entire configuration class will take effect, determine whether the current application is a web app, if so, the current configuration class takes effect@ConditionalOnClass (characterencodingfilter.class)//determine whether the current project has no such type of CHARACTERENCODINGFILTER;SPRINGMVC in the garbled solution of the filter;@ConditionalOnProperty (Prefix="spring.http.encoding", value ="enabled", matchifmissing =true)//determine if there is a configuration spring.http.encoding.enabled in the configuration file, and if it does not exist, the judgment is established.//even if the pring.http.encoding.enabled=true is not configured in our configuration file, it is also in effect by default; Public classhttpencodingautoconfiguration {//He has mapped the configuration file with Springboot Privatefinal Httpencodingproperties properties; //in the case of only one parameter constructor, the value of the argument will be taken in the Publichttpencodingautoconfiguration (httpencodingproperties properties) { This. Properties =properties; } @Bean//add a component to the container, some values of this component need to be obtained from the properties@ConditionalOnMissingBean (Characterencodingfilter.class)//Judging the container does not have this component? 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; }
5), all the properties that can be configured in the configuration file are encapsulated in the Xxxxproperties class, and the configuration file can be configured to refer to the attribute class of a function.
" spring.http.encoding ") // gets the specified value from the configuration file and binds the Bean's properties Public class httpencodingproperties { publicstatic final Charset Default_charset = Charset.forname ("UTF-8");
Essence:
? 1), Springboot boot will load a large number of automatic configuration classes
? 2), we look at the function we need there is no springboot default written automatic configuration class;
? 3), let's see exactly which components are configured in this auto-configuration class, (as long as we have the components we want to use, we don't need to configure them anymore)
? 4), when adding components to the automatic configuration class in the container, some attributes are obtained from the properties class. We can specify the values of these properties in the configuration file;
Xxxxautoconfigurartion: Automatic configuration class;
Adding components to the container
Xxxxproperties: Encapsulates the relevant properties in the configuration file;
2. Details
1, @Conditional derived annotations (Spring annotated version of the original @conditional effect)
Function: Must be @conditional specified conditions, only to add components to the container, the configuration of all the contents in order to take effect;
@Conditional Extended Annotations |
function (determines whether the current specified condition is met) |
@ConditionalOnJava |
Whether the Java version of the system meets the requirements |
@ConditionalOnBean |
The specified bean exists in the container; |
@ConditionalOnMissingBean |
The specified bean does not exist in the container; |
@ConditionalOnExpression |
Satisfies the SPEL expression designation |
@ConditionalOnClass |
The specified class is in the system |
@ConditionalOnMissingClass |
There are no classes specified in the system |
@ConditionalOnSingleCandidate |
There is only one specified bean in the container, or the bean is the preferred bean |
@ConditionalOnProperty |
Whether the specified property has a specified value in the system |
@ConditionalOnResource |
Whether the specified resource file exists under the class path |
@ConditionalOnWebApplication |
is currently a web environment |
@ConditionalOnNotWebApplication |
Not currently a Web environment |
@ConditionalOnJndi |
JNDI exists specified item |
The automatic configuration class must be under certain conditions to take effect;
How do we know which auto-configuration classes are in effect;
= = We can let the console print the automatic configuration report by enabling the Debug=true property; , so that we can easily know which auto-configuration classes take effect;
=========================AUTO-CONFIGURATION Report=========================Positive matches: (Automatic configuration class enabled)-----------------Dispatcherservletautoconfiguration matched:-@ConditionalOnClass found requiredclass 'Org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwantedclass(onclasscondition)-@ConditionalOnWebApplication (required) found Standardservletenvironment (onwebapplicationcondition) Negat Ive matches: (no boot, no matching automatic configuration Class)-----------------Activemqautoconfiguration:did not match:-@ConditionalOnClass did not find required classes'javax.jms.ConnectionFactory','org.apache.activemq.ActiveMQConnectionFactory'(onclasscondition) aopautoconfiguration:did not match:-@ConditionalOnClass did not find required classes'Org.aspectj.lang.annotation.Aspect','Org.aspectj.lang.reflect.Advice'(onclasscondition)
Spring Boot automatic configuration principle