Early Spring
projects need to add cumbersome configurations xml
, such as MVC
, transactions, database connections and other cumbersome configurations. Spring Boot
With the emergence of , there is no need for these cumbersome configurations, because Spring Boot
based on the concept that conventions are greater than configurations , when the project starts, the agreed configuration classes are automatically configured into IOC
the container. These are all due to Spring Boot
the automatic configuration feature.
How Spring Boot implements automatic configuration
Spring Boot
All need to create a mian
startup class, and the startup class contains @SpringBootApplication
annotations, 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
@SpringBootApplication
There @EnableAutoConfiguration
are :
@Import annotation
@EnableAutoConfiguration
There @Import
are :
AutoConfigurationImportSelector类
@Import
Annotations import AutoConfigurationImportSelector
classes:
selectImports() method
AutoConfigurationImportSelector
The class finds selectImports
the method , which has getAutoConfigurationEntry
the method:
SpringFactoriesLoader.loadFactoryNames() 方法
getAutoConfigurationEntry
method SpringFactoriesLoader.loadFactoryNames()
scans all packages META-INF/spring.factories
containing :jar
spring-boot-autoconfigure-xxx.jar
The project includes META-INF/spring.factories
a file, spring.factories
which is in the form of a key-value pair, and scans the @EnableAutoConfiguration
corresponding class under the file:
Summary of automatic assembly process
Spring Boot
Principle of automatic configuration- 1.
@EnableAutoConfiguration
Annotate the importedAutoConfigurationImportSelector
class. - 2. Execute
selectImports
the method call toSpringFactoriesLoader.loadFactoryNames()
scan alljar
the correspondingMETA-INF/spring.factories
files below. - 3. Defined as
@EnableAutoConfiguration
correspondingvalue
, assemble these assembly conditions intoIOC
the container.
- 1.
bean
Simply speaking, automatic assembly is to automatically load third-party componentsIOC
into the container without writingbean
related configurations. It conforms to the concept of agreement rather than configuration .Spring Boot
Based 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 theIOC
container according to the agreement, without the need for developers to manually add configuration, speeding up development efficiency.