SpringBoot automatic assembly source code analysis

Early Springprojects need to add cumbersome configurations xml, such as MVC, transactions, database connections and other cumbersome configurations. Spring BootWith the emergence of , there is no need for these cumbersome configurations, because Spring Bootbased on the concept that conventions are greater than configurations , when the project starts, the agreed configuration classes are automatically configured into IOCthe container. These are all due to Spring Bootthe automatic configuration feature.

How Spring Boot implements automatic configuration

Spring BootAll need to create a mianstartup class, and the startup class contains @SpringBootApplicationannotations, from the startup class, step by step to explore the source code.

@SpringBootApplication annotation

Spring Boot There is an annotation on the startup class  @SpringBootApplication:

@EnableAutoConfiguration annotation

@SpringBootApplicationThere @EnableAutoConfigurationare :

 @Import annotation

@EnableAutoConfigurationThere @Importare :

AutoConfigurationImportSelector类

@ImportAnnotations import AutoConfigurationImportSelectorclasses:

selectImports() method

AutoConfigurationImportSelectorThe class finds selectImportsthe method , which has getAutoConfigurationEntrythe method:

SpringFactoriesLoader.loadFactoryNames() 方法

getAutoConfigurationEntrymethod SpringFactoriesLoader.loadFactoryNames()scans all packages META-INF/spring.factoriescontaining :jar

spring-boot-autoconfigure-xxx.jarThe project includes META-INF/spring.factoriesa file, spring.factorieswhich is in the form of a key-value pair, and scans the @EnableAutoConfigurationcorresponding class under the file:

Summary of automatic assembly process

  • Spring BootPrinciple of automatic configuration
    • 1. @EnableAutoConfigurationAnnotate the imported AutoConfigurationImportSelectorclass.
    • 2. Execute selectImportsthe method call to SpringFactoriesLoader.loadFactoryNames()scan all jarthe corresponding META-INF/spring.factoriesfiles below.
    • 3. Defined as @EnableAutoConfigurationcorresponding value, assemble these assembly conditions into IOCthe container.
  • beanSimply speaking, automatic assembly is to automatically load third-party components IOCinto the container without writing beanrelated configurations. It conforms to the concept of agreement rather than configuration .
  • Spring BootBased on the idea that convention is greater than configuration , if there is no additional configuration for configuration, the default configuration will use the agreed default value, and configure it in the IOCcontainer according to the agreement, without the need for developers to manually add configuration, speeding up development efficiency.

Guess you like

Origin blog.csdn.net/gongzi_9/article/details/129803084
Recommended