Springboot sentiment edify-@SpringBootApplication annotation Analysis

Source: Internet
Author: User
Tags throw exception

To undertake the previous text springboot sentiment edify [email protected] annotation analysis, this article will be based on the above @SpringBootApplication annotation to make a simple analysis

@SpringBootApplication

This annotation is one of the most concentrated annotations in Springboot and the most widely used annotation. The official also use this note to start the Spring service, we look at the source code

@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 {    @AliasFor(annotation = EnableAutoConfiguration.class)    Class<?>[] exclude() default {};    @AliasFor(annotation = EnableAutoConfiguration.class)    String[] excludeName() default {};    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")    String[] scanBasePackages() default {};    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")    Class<?>[] scanBasePackageClasses() default {};}

The code above shows that it integrates @EnableAutoConfiguration and @ComponentScan two major annotations, which are specified by default.

  1. Attributes exclude and excludename, whose default is null, and the specified words are eventually resolved by Enableautoconfiguration.class .

  2. Attributes scanbasepackages and scanbasepackageclasses, whose default is null, and the specified words are eventually resolved by Componentscan.class .

  3. By default, the @SpringBootApplication package name of the class in which the annotation is located is used as the Beandefinition scan path.
    Masking the org.springframework.boot.autoconfigure.EnableAutoConfiguration class collection specified by attributes in the Meta-inf\spring.factories file during scanning

  4. Support multiple @ComponentScan annotations with annotations at the same time @SpringBootApplication

@ComponentScan Annotations have been understood in the previous article, the author here for the @EnableAutoConfiguration annotation For detailed analysis

@EnableAutoConfiguration

Simply from the English word is open automatic injection of the meaning, the specific words of the author or according to the source code to interpret. First look at the source code of the annotations

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import(AutoConfigurationImportSelector.class)public @interface EnableAutoConfiguration {    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";    /**     * Exclude specific auto-configuration classes such that they will never be applied.     * @return the classes to exclude     */    Class<?>[] exclude() default {};    /**     * Exclude specific auto-configuration class names such that they will never be     * applied.     * @return the class names to exclude     * @since 1.3.0     */    String[] excludeName() default {};}

It uses the @Import annotations We mentioned earlier, so we focus on the Autoconfigurationimportselector.class we've introduced.

Autoconfigurationimportselector

It is the implementation class of the Deferredimportselector.class interface, where we view the method of the replication directly selectimports ()

    @Override public string[] Selectimports (annotationmetadata annotationmetadata) {//Spring.boot.enableautoco        Nfiguration property Read, default to True if (!isenabled (Annotationmetadata)) {return no_imports; }//Read all meta-inf\spring-autoconfigure-metadata.properties files Autoconfigurationmetadata Autoconfigur                        Ationmetadata = Autoconfigurationmetadataloader. Loadmetadata (This.beanclassloader);                Gets the property corresponding to the @enableautoconfiguration on the corresponding class annotationattributes attributes = GetAttributes (annotationmetadata); Read all <org.springframework.boot.autoconfigure.EnableAutoConfiguration> properties from META-INF\SPR Ing.factories list<string> configurations = getcandidateconfigurations (Annotationmetadata, att        Ributes);                Configurations = removeduplicates (configurations);    Read Exclude/excludename property or Spring.autoconfigure.exclude property    Set<string> exclusions = getexclusions (annotationmetadata, attributes);         Make sure the assignable exclusions is present in classpath and configurations collection, or would throw exception        Checkexcludedclasses (configurations, exclusions);        Configurations.removeall (exclusions);        Filter the present Configurations configurations = filter (configurations, autoconfigurationmetadata); Fire the autoconfigurationimportevent by Autoconfigurationimportlistener.class fireautoconfigurationimportevents                        (configurations, exclusions);    return Stringutils.tostringarray (configurations); }

The above steps are summarized here

  1. The environment variable spring.boot.enableautoconfigurationis prioritized and no class is introduced if it is specified as false. Default is True

  2. Read all the meta-inf\spring-autoconfigure-metadata.properties files in the CLASSPATH environment, Load all of the properties in the save to Autoconfigurationmetadata

  3. Gets the @enableautoconfiguration corresponding property on the corresponding class, which is actually the exclude property and the excludename property

  4. Read the properties of all the meta-inf\spring.factories files in the CLASSPATH environment org.springframework.boot.autoconfigure.EnableAutoConfiguration and get the Configurations collection

  5. The exclusions collection is obtained based on the configuration read in the third step and the spring.autoconfigure.exclude configuration specified by the environment variable

  6. Make sure that the exclusions collection is a subset of the configurations collection, and that the class in the Exclusions collection is present in the CLASSPATH environment. Otherwise the exception is thrown

  7. Filters out unfiltered configurations collections based on the exclusions set above.

  8. Based on the 7th Filter Configurations collection, and then on the basis of Autoconfigurationmetadata for the ConditionalOnClass property filter round
    For example: org.springframework.boot.autoconfigure.cache.cacheautoconfiguration.conditionalonclass= Org.springframework.cache.CacheManager
    Indicates that if you want to apply cacheautoconfiguration, you have to ensure that the Org.springframework.cache.CacheManager class exists

  9. Triggering autoconfigurationimportevent Events

  10. Returns the configurations collection after filtering

The author here lists the enableautoconfiguration default attributes in the Spring-boot-autoconfigure-2.0.3.realease package, the spring.factories attributes are too many, the following excerpt

# 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.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.web.client.RestTemplateAutoConfiguration, Org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,... Org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration, Org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration, Org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, Org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, Org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration, Org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, Org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration, Org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration, Org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration, Org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

Of course, users can also customize to implement the configuration classes that need to be injected automatically.

Summarize

@SpringBootApplication annotations contain @EnableAutoConfiguration annotations and @ComponentScan annotations, so the two annotations are combined to match the @Configuration Annotations will enable the Springboot to function.
In this, the@EnableAutoConfiguration annotation is the most important, its extensibility is very good, convenient springboot seamlessly docking different plug-ins (NoSQL plug-ins, web plugins, JMX protocol plug-ins, etc.), the reader needs to analyze well.

Next section Trailer

By referring to the above-mentioned automatic annotations, it is found that @Conditional and autoconfigureafter annotations are conditional judgments, and before they are thoroughly understood Springboot integrate other plugins, You must have a deep understanding of the two annotations.

Springboot sentiment edify [email protected] annotation 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.