Spring Boot's auto-configuration mechanism is one of its important features , greatly simplifying the configuration of Spring applications . The core idea of auto-configuration is based on the dependencies in the class path , environment configuration and custom code for intelligent configuration , avoiding the developer to manually write a large number of sample code .
Next, I will introduce the Spring Boot auto-configuration process in detail, the core principles and key components involved, and combined with the source code for in-depth analysis.
I. Spring Boot auto-configuration workflow
-
@SpringBootApplication
explanatory note
The starting point for auto-configuration is usually@SpringBootApplication
annotation, which is a combination annotation that contains three important annotations:-
@SpringBootConfiguration
: tagged as a Spring configuration class, similar to the@Configuration
。 -
@EnableAutoConfiguration
: Enables Spring Boot's auto-configuration mechanism. -
@ComponentScan
: Scans all Spring components under the current package and its sub-packages.
included among these
@EnableAutoConfiguration
is the core of autoconfiguration, which guides the autoconfiguration mechanism. -
-
@EnableAutoConfiguration
cap (a poem)AutoConfigurationImportSelector
@EnableAutoConfiguration
annotation serves to tell Spring Boot to automatically configure the Spring application context when it starts. This annotation introduces theAutoConfigurationImportSelector
, which is automatically configured for the core processor.@Target() @Retention() @Documented @Inherited @AutoConfigurationPackage @Import() public @interface EnableAutoConfiguration { }
AutoConfigurationImportSelector
Classes are retrieved from the configuration file (usually) reads all autoconfiguration classes and imports them into the application context.
-
file
The autoconfiguration class is passedspring-boot-autoconfigure
modularMETA-INF/
file to configure it. This file lists all the configuration classes that can be autoloaded:=\ ,\ ,\ ,\ ...
These configuration classes are optionally loaded at Spring Boot startup based on the current environment conditions.
-
Conditional assembly (
@Conditional
(series of notes)
Spring Boot does not blindly load all autoconfiguration classes. Each autoconfiguration class is usually loaded using the@Conditional
series of annotations for conditional loading. The most common conditional annotations are:-
@ConditionalOnClass
: Takes effect when a class exists in the class path. -
@ConditionalOnMissingBean
: Takes effect when a bean does not exist in the Spring context. -
@ConditionalOnProperty
: Takes effect when a configuration attribute meets certain conditions. -
@ConditionalOnBean
: Takes effect when a bean exists in the Spring context.
For example.
DataSourceAutoConfiguration
Only if there are data source-related dependencies in the project (such as theclass) when it is loaded.
-
-
Example of an autoconfiguration class:
DataSourceAutoConfiguration
In Spring Boot
DataSourceAutoConfiguration
is the autoconfiguration class that configures the data source, and its source code is as follows:@Configuration @ConditionalOnClass() @EnableConfigurationProperties() @Import({, }) public class DataSourceAutoConfiguration { @Bean @ConditionalOnMissingBean public DataSource dataSource(DataSourceProperties properties) { // Create and return DataSource boyfriend return ().build(); } }
-
@ConditionalOnClass()
: only if the class path has aDataSource
The auto-configuration of the data source is performed only when the class. -
@ConditionalOnMissingBean
: If there are no otherDataSource
bean, then one is automatically configured.
This condition-based configuration approach ensures Spring Boot's flexibility by allowing users to skip certain auto-configurations by overriding default beans or by not meeting conditions.
-
Second, the core steps of Spring Boot auto-configuration
-
Collection of auto-configuration classes
At startup.AutoConfigurationImportSelector
through (a gap)file to read all the autoconfiguration classes through the
@Import
Import these classes. -
conditionality check
The loading of autoconfiguration classes is not unconditional; Spring Boot loads the classes based on the@Conditional
annotation performs conditional checking to ensure that only eligible autoconfiguration classes take effect. -
Inject the required bean
Once the autoconfiguration classes pass the conditional check, Spring Boot registers the required beans against these configuration classes. e.g.DataSourceAutoConfiguration
The bean associated with the data source is automatically configured. -
Allow users to override auto-configuration
Autoconfiguration is not mandatory. Users can override the default behavior of autoconfiguration by explicitly declaring their own beans. For example, if the user defines in their own configuration class theDataSource
If the data source is not automatically configured by Spring Boot, then Spring Boot will no longer configure the data source.
Third, the actual case of Spring Boot auto-configuration
-
Web application auto-configuration
In a Spring Boot web application, theDispatcherServletAutoConfiguration
is responsible for auto-configuring core Spring MVC components such as theDispatcherServlet
、RequestMappingHandlerMapping
etc.- If the project has a
spring-web
dependence, thenDispatcherServletAutoConfiguration
It will be loaded automatically. - If not manually defined
DispatcherServlet
Spring Boot automatically creates aDispatcherServlet
and configured into the Spring container.
- If the project has a
-
Database connection pool auto-configuration
Spring Boot also automatically configures database connection pools (e.g., HikariCP, Tomcat JDBC, etc.), which depend on the project'sspring-boot-starter-data-jpa
orspring-boot-starter-jdbc
Dependency.-
DataSourceAutoConfiguration
cap (a poem)DataSourceProperties
Jointly responsible for automated configuration of data sources. - If a connection pooling class exists in the class path (such as the
HikariDataSource
), then Spring Boot automatically configures connection pooling.
At the same time, the user can
file to customize the connection pool configuration:
=jdbc:mysql://localhost:3306/mydb =root =secret -pool-size=10
-
-
Spring Security Auto-Configuration
When introducingspring-boot-starter-security
When relying on it, Spring Boot automatically configures the security mechanism and provides HTTP Basic authentication by default.-
SecurityAutoConfiguration
The infrastructure responsible for automating the configuration of Spring Security. - If you need to customize the security policy, you can do so by customizing the
WebSecurityConfigurerAdapter
to override the default configuration.
-
Fourth, the benefits of Spring Boot auto-configuration
- Greatly simplifies configuration: Developers no longer need to write configuration code for each infrastructure component; the auto-configuration mechanism automatically injects the required beans based on project dependencies.
- dexterity: The auto-configuration does not tie developers down. Developers can easily override the default autoconfiguration with a custom configuration.
- Covenant is better than allocation: Spring Boot follows the principle of "convention over configuration", which allows Spring Boot to perform complex initialization tasks with little configuration.
V. Spring Boot auto-configuration and Spring auto-assembly differences
-
Spring Automated Assembly: means that by
@Autowired
It focuses on injecting already configured beans. - Spring Boot Auto-Configuration: It is the process of automatically configuring Spring components based on the dependencies and environment information in the class path. It is responsible for creating and configuring the required infrastructure beans.
To summarize, Spring Boot's autoconfiguration mechanism works via the@EnableAutoConfiguration
Startup, based on The configuration in the
@Conditional
Conditional judgments are automatically injected into the required beans, simplifying the developer's configuration work while retaining flexible customization capabilities.