Talk about the automatic configuration of Spring Boot

introduce

Spring Boot's automatic configuration is one of its core features, allowing us to quickly build a Spring application.

features

  1. According to the Jar package dependencies in the classpath, the basic configuration items of Spring are automatically configured. For example, Spring Data JPA is automatically configured in the classpath according to spring-data-jpa.
  2. Provides a series of out-of-the-box automatic configuration implementations, which solves the problem of configuring a large number of beans in configuration files. These automatic configuration implementations are in the spring-boot-autoconfigure package.
  3. Automatic configuration will decide whether to enable it according to the user-defined Bean, which can be customized and rewritten. Conditional configuration is achieved through the @Conditional annotation.
  4. Provides many out-of-the-box starter dependencies, which further simplifies dependency management, such as spring-boot-starter-web, etc.
  5. Automatic configuration will only load the configuration items that are actually used, through conditional configurations such as @ConditionalOnClass and @ConditionalOnMissingBean.
  6. Provides quasi-production external configuration file support, such as application.properties.
  7. The automatic configuration switch can be controlled by @EnableAutoConfiguration.

accomplish

1.@SpringBootApplication

This annotation contains @EnableAutoConfiguration, which is used to enable Spring Boot's automatic configuration function.

@EnableAutoConfiguration will use AutoConfigurationImportSelector to import some automatic configuration classes to the container.

2. SpringFactoriesLoader

Spring Boot will load the auto-configuration classes in the META-INF/spring.factories file through SpringFactoriesLoader.

Many automatic configuration implementation classes are configured in the spring.factories file, such as:

org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration

org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

When there is a specified dependency in the classpath, the auto-configuration class corresponding to the dependency will be instantiated.

3.@Conditional

The @Conditional annotation is usually used on the automatic configuration class to control whether the configuration takes effect according to different conditions.

Commonly used are: @ConditionalOnClass, @ConditionalOnMissingBean, etc.

write at the end

If you are interested in related articles, you can pay attention to the official account "Architecture Hall", and will continue to update AIGC, java basic interview questions, netty, spring boot, spring cloud and other series of articles, and a series of dry goods will be delivered at any time!

Guess you like

Origin blog.csdn.net/jinxinxin1314/article/details/132540272