Completely understand the process of automatic configuration of spring boot in one article (recommended)
Spring Boot's automatic configuration mechanism is one of its important features, greatly simplifying the configuration of Spring applications. The core idea of automatic configuration is to intelligently configure based on dependencies, environment configuration and custom code in the class path, avoiding developers manually writing a large amount of boilerplate code.
Next, I will introduce the process of automatic configuration of Spring Boot, the core principles and the key components involved in detail, and conduct in-depth analysis based on the source code.
1. Spring Boot automatic configuration workflow
-
@SpringBootApplication
NoteThe starting point of automatic configuration is usually@SpringBootApplication
Annotation, it is a combination annotation, which contains three important annotations:in
@EnableAutoConfiguration
is the core of automatic configuration, which guides the automatic configuration mechanism.-
@SpringBootConfiguration
: Marked as a Spring configuration class, similar to@Configuration
。 -
@EnableAutoConfiguration
: Enable Spring Boot's automatic configuration mechanism. -
@ComponentScan
: Scan all Spring components under the current package and its subpackages.
-
@EnableAutoConfiguration
andAutoConfigurationImportSelector@EnableAutoConfiguration
The purpose of the annotation is to tell Spring Boot to automatically configure the Spring application context when it is started. This annotation introducesAutoConfigurationImportSelector
, this is the core processor that is automatically configured.
@Target() @Retention() @Documented @Inherited @AutoConfigurationPackage @Import() public @interface EnableAutoConfiguration { }
AutoConfigurationImportSelector
The class will be from the configuration file (usually) Read all the autoconfiguration classes and import them into the application context.
documentAutomatic configuration class is passed
spring-boot-autoconfigure
ModularMETA-INF/
File to configure. This file lists all configuration classes that can be loaded automatically:
=\ ,\ ,\ ,\ ...
These configuration classes are selectively loaded according to the current environment conditions when Spring Boot is started.
-
Conditional assembly (
@Conditional
Series of notes)Spring Boot does not blindly load all autoconfiguration classes. Each automatic configuration class is usually used@Conditional
Series of annotations for conditional loading. The most common conditional annotations are:For example,
DataSourceAutoConfiguration
Only data source-related dependencies exist in the project (such aswill be loaded only when class).
-
@ConditionalOnClass
: Effective only when a certain class exists in the classpath. -
@ConditionalOnMissingBean
: Effective when there is no bean in the Spring context. -
@ConditionalOnProperty
: Take effect only when a configuration property meets a specific condition. -
@ConditionalOnBean
: Effective when a bean exists in the Spring context.
-
Automatic configuration class example:DataSourceAutoConfiguration
Spring BootDataSourceAutoConfiguration
It is an automatic configuration class for configuring data sources, and its source code is as follows:
@Configuration @ConditionalOnClass() @EnableConfigurationProperties() @Import({, }) public class DataSourceAutoConfiguration { @Bean @ConditionalOnMissingBean public DataSource dataSource(DataSourceProperties properties) { // Create and return the DataSource object return ().build(); } }
This condition-based configuration ensures flexibility in Spring Boot, allowing users to skip certain automatic configurations by overwriting the default bean or not meeting the conditions.
-
@ConditionalOnClass()
: Only if it exists under the classpathDataSource
Automatic configuration of the data source is only carried out when the class is used. -
@ConditionalOnMissingBean
: If there is no other in the Spring contextDataSource
Bean, then automatically configure one.
2. The core steps of Spring Boot automatic configuration
-
Collect automatic configuration classesAt startup,
AutoConfigurationImportSelector
fromRead all automatic configuration classes in the file and pass
@Import
Import these classes. -
Condition checkThe loading of the automatic configuration class is not unconditional, Spring Boot will use it according to
@Conditional
Annotation performs condition checks to ensure that only automatic configuration classes that meet the conditions will take effect. -
Inject the required beansOnce the automatic configuration class passes the conditional check, Spring Boot registers the required beans based on these configuration classes. For example,
DataSourceAutoConfiguration
The data source-related beans will be automatically configured. -
Allow users to override automatic configurationAutomatic configuration is not mandatory. Users can override the default behavior of auto-configuration by explicitly declaring their own beans. For example, if the user defines the
DataSource
, then Spring Boot will no longer automatically configure the data source.
3. Actual cases of automatic configuration of Spring Boot
-
Automatic configuration of web applicationsIn Spring Boot Web Applications,
DispatcherServletAutoConfiguration
Responsible for automatically configuring the core components of Spring MVC, such asDispatcherServlet
、RequestMappingHandlerMapping
wait.- If there is a project
spring-web
Dependency, thenDispatcherServletAutoConfiguration
It will be loaded automatically. - If not manually defined
DispatcherServlet
, Spring Boot will automatically create aDispatcherServlet
and configure it into Spring container.
- If there is a project
Automatic configuration of database connection poolSpring Boot will also automatically configure database connection pools (such as HikariCP, Tomcat JDBC, etc.), which depends on the projectspring-boot-starter-data-jpa
orspring-boot-starter-jdbc
Dependence.
At the same time, users can useFile custom connection pool configuration:
=jdbc:mysql://localhost:3306/mydb =root =secret -pool-size=10
-
DataSourceAutoConfiguration
andDataSourceProperties
Together are responsible for automatically configuring the data source. - If there is a connection pooling class in the classpath (such as
HikariDataSource
), then Spring Boot will automatically configure the connection pool. -
Spring Security Automatic configurationWhen introduced
spring-boot-starter-security
When dependency is made, Spring Boot will automatically configure the security mechanism and provide the HTTP Basic authentication mechanism by default.-
SecurityAutoConfiguration
Responsible for automatically configuring Spring Security's infrastructure. - If you need to customize your security policy, you can customize it
WebSecurityConfigurerAdapter
to override the default configuration.
-
4. The benefits of Spring Boot automatic configuration
- Greatly simplify configuration work: Developers no longer need to write configuration code for each infrastructure component, and the automatic configuration mechanism automatically injects the required beans based on project dependencies.
- flexibility: Automatic configuration does not restrict developers. Developers can easily override the default automatic configuration through custom configurations.
- Conventions are better than configuration: Spring Boot follows the principle of "convention is better than configuration". Spring Boot can complete complex initialization work with just a small amount of configuration.
5. The difference between Spring Boot automatic configuration and Spring automatic assembly
-
Spring automatic assembly: refers to passing
@Autowired
and other annotations, automatically inject dependency beans according to the type. It focuses on injecting already configured beans. - Spring Boot Automatic Configuration: It is a process of automatically configuring Spring components based on dependencies and environment information in the classpath. It is responsible for creating and configuring the required infrastructure beans.
In summary, Spring Boot's automatic configuration mechanism passes@EnableAutoConfiguration
Start, based onConfiguration and
@Conditional
Conditional judgment, automatic injection of required beans simplifies the developer's configuration work while retaining flexible customization capabilities.
This is the article about thoroughly understanding the process of spring boot automatic configuration in this article. For more related spring boot automatic configuration content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
How to create a normal binary tree in java
This article mainly introduces how Java creates a normal binary tree operation, which has good reference value and hopes to be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice2021-07-07Java SE's understanding of generics
This article mainly introduces Java SE to understand generics. The content of the article is detailed and simple and easy to understand. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2023-01-01Detailed explanation of the proxy mode in the design mode and its implementation in Java programs
The proxy mode is mainly divided into static proxy and dynamic proxy, so that the client users can operate objects through the set proxy. The following is a detailed explanation of the proxy mode in the design mode and its implementation in Java programs.2016-05-05A brief analysis of the use of Java drawing mode
This article mainly introduces a brief analysis of the use of Java's drawing mode. It roughly lists some things that can be done in XOR mode with a small example. Friends who need it can refer to it.2015-10-10How to implement Java access to Https requests through certificates
This article mainly introduces how Java can access Https requests through certificates, which is of good reference value and hopes to be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice2022-01-01A brief discussion on the difference between replace() and replaceAll() in java
This article mainly introduces the difference between replace() and replaceAll() in Java. Both are commonly used methods of replacing characters. Interested friends can refer to it.2015-11-11Java backend realizes Alipay payment interface and Alipay order query interface (front end is APP)
This article mainly introduces the implementation of the Alipay payment interface and the Alipay order query interface (the front-end is APP), which is very practical. Friends who need it can refer to it.2018-08-08A brief discussion on the process of Java files being executed
Since I learned Java, I have always started with syntax and class libraries. The most basic and basic java compilation process is often forgotten by me. Let me first explain a sentence I heard in the first lesson of learning Java, "java is a semi-interpreted language." What is a semi-interpreted language. This article will introduce the process of Java files being executed.2021-06-06Detailed explanation of input and output mapping and dynamic Sql graphics in Mybatis
This article mainly introduces relevant materials on the input and output mapping and dynamic Sql in Mybatis. The article introduces the sample code in detail, which has certain reference learning value for everyone's study or work. Friends who need it, let's learn together.2019-02-02How to build SQL statements in Mybatis
This article mainly introduces how Mybatis builds SQL statement issues, which are of great reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2023-12-12