Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Principle of SpringBoot automatic assembly

SpringBoot automatic assembly principle is what, different people may have different understanding, but as a programmer, the most authoritative is to look at the source code, the following look at SpringBoot related source code, understand the principle of SpringBoot automatic assembly

@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 {
}
Copy the code

Enter the SpringBootApplication annotation to see the EnableAutoConfiguration annotation

The main purpose of the @enable annotation is to assemble the beans of related components into the IOC container

Enter EnableAutoConfiguration.

@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
    * @since1.3.0 * /
   String[] excludeName() default {};

}
Copy the code

The @AutoConfigurationPackage is used to scan all components in the package and subpackages of the class that uses the annotation into the SpringIOC container. @ Import annotations into a AutoConfigurationImportSelector class AutoConfigurationImportSelector implement Import the configuration class

AutoConfigurationImportSelector implements ImportSelector interface selectImports method returns a String array, the array is specified in the need to assembly into the IOC container

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
   if(! isEnabled(annotationMetadata)) {return NO_IMPORTS;
   }
   AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
         .loadMetadata(this.beanClassLoader);
   AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(
         autoConfigurationMetadata, annotationMetadata);
   return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
Copy the code
  1. AutoConfigurationMetadataLoader. LoadMetadata from the meta-inf/spring – autoconfigure – metadata. The properties of load automatic assembly condition of metadata, That is, only beans that meet the conditions can be assembled.
  2. Collection of eligible configuration class autoConfigurationEntry. GetConfigurations (), complete the automatic assembly

Does not perform in the AutoConfigurationImportSelector selectImports method, But by ConfigurationClassPostProcessor processConfigBeanDefinitions method of scanning and register all the Bean configuration class.

protected AutoConfigurationEntry getAutoConfigurationEntry( AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
   if(! isEnabled(annotationMetadata)) {return EMPTY_ENTRY;
   }
   AnnotationAttributes attributes = getAttributes(annotationMetadata);
   List<String> configurations = getCandidateConfigurations(annotationMetadata,
         attributes);
   configurations = removeDuplicates(configurations);
   Set<String> exclusions = getExclusions(annotationMetadata, attributes);
   checkExcludedClasses(configurations, exclusions);
   configurations.removeAll(exclusions);
   configurations = filter(configurations, autoConfigurationMetadata);
   fireAutoConfigurationImportEvents(configurations, exclusions);
   return new AutoConfigurationEntry(configurations, exclusions);
}
Copy the code
  1. GetAttributes Obtains attributes such as exclude excludeName in the @enableAutoConfiguration annotation
  2. GetCandidateConfigurations get all automatic assembly configuration class
  3. RemoveDuplicates the method to delete duplicate configuration items
  4. The getExclusions method removes configuration classes that do not need automatic assembly based on the exclude attribute configured in the @enableAutoConfiguration annotation.
  5. FireAutoConfigurationImportEvents methods broadcast events
  6. Finally, a collection of configuration classes is returned after multiple layers of judgment and filtering.

GetCandidateConfigurations method

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
   List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
         getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
   Assert.notEmpty(configurations,
         "No auto configuration classes found in META-INF/spring.factories. If you "
               + "are using a custom packaging, make sure that file is correct.");
   return configurations;
}
Copy the code

The SpringFactoriesLoader scans the meta-INF/Spring. factories file in the CLASspath and obtains the value based on the Key.

Conclusion:

  1. Import configuration classes via @import
  2. AutoConfigurationImportSelector class implements ImportSelector interface, rewrite selectImports method, is used to realize the selective assembly in batch configuration class
  3. Using the SpringFactoriesLoader mechanism, you can scan the meta-INF/Spring. factories file in the CLASspath path and read the configuration classes for automatic assembly
  4. By filtering conditions, the configuration classes that do not meet the conditions are removed to complete automatic assembly.

Well, this is the principle of SpringBoot automatic assembly, to give you a simple analysis, if you think it is good, welcome to leave a message and praise, everyone’s praise is the biggest encouragement to me, I will continue to more, improve their own at the same time to share more good articles.