SpringBoot automatic assembly principle

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

@SpringBootApplication@EnableAutoConfiguration Notes inside  :

AutoConfigurationImportSelector类

@EnableAutoConfigurationAnnotation import AutoConfigurationImportSelectorclass:

selectImports() method

AutoConfigurationImportSelectorThe class finds  selectImports the method, which has getAutoConfigurationEntrythe method:

SpringFactoriesLoader.loadFactoryNames() 方法

getAutoConfigurationEntrymethod by SpringFactoriesLoader.loadFactoryNames() scanning 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:

Automatic configuration is mainly implemented @EnableAutoConfigurationby adding @EnableAutoConfigurationannotations and importing classes. The methods AutoConfigurationImportSelectorin it scan all the included packages and assemble all the classes corresponding to the full name of the annotations into the container.selectImportsSpringFactoriesLoader.loadFactoryNames()META-INF/spring.factoriesjarkey@EnableAutoConfigurationvalueIOC

Debug verification

Turn on Debugthe debug mode, set a breakpoint in getCandidateConfigurationsthe method SpringFactoriesLoader.loadFactoryNames(), and view the returned configurationscollection:

The first element is tk.mybatis.mapper.autoconfigure.MapperAutoConfigurationdue to the introduced 通用mapperdependency:

Principle of automatic configuration

Principle process summary

From the source code viewed above, we can know that Spring Bootthe automatic configuration is mainly @EnableAutoConfigurationrealized by @EnableAutoConfigurationannotating imported AutoConfigurationImportSelectorclasses, scanning all packages containing files through selectImportsmethod calls , and injecting the corresponding classes in the files into the container.SpringFactoriesLoader.loadFactoryNames()META-INF/spring.factoriesjarspring.factories@EnableAutoConfigurationIOC

After these attributes are automatically configured , IOCthere is no need to manually configure them . The idea in the convention is to add the required configuration to the container in an agreed manner.beanSpring Boot约定大于配置IOC

Conditions for automatic configuration to take effect

Does that mean that spring.factoriesthe configuration corresponding to the file will be loaded into IOCthe container? For example, the following Kafkaautomatic configuration class:

@Configuration
@ConditionalOnClass(KafkaTemplate.class)
@EnableConfigurationProperties(KafkaProperties.class)
@Import({ KafkaAnnotationDrivenConfiguration.class, KafkaStreamsAnnotationDrivenConfiguration.class })
public class KafkaAutoConfiguration {

	private final KafkaProperties properties;

	private final RecordMessageConverter messageConverter;

	public KafkaAutoConfiguration(KafkaProperties properties, ObjectProvider<RecordMessageConverter> messageConverter) {
		this.properties = properties;
		this.messageConverter = messageConverter.getIfUnique();
	}

	@Bean
	@ConditionalOnMissingBean(KafkaTemplate.class)
  public KafkaTemplate<?, ?> kafkaTemplate(ProducerFactory<Object, Object> kafkaProducerFactory,
			ProducerListener<Object, Object> kafkaProducerListener) {
      ....
      }

There are several annotations in it:

@ConditionalOnClass
@ConditionalOnMissingBean
  • @ConditionalOnClassIndicates that the configuration class will only be configured if there is a class in the class path. This configuration class will be automatically configured only when the relevant dependencies of the " Hospital Certificate Template " are introduced.
  • @ConditionalOnMissingBeanIndicates that only if the corresponding class does not exist, beanthe class will be automatically configured.

So spring.factoriesnot all of them beanwill be assembled into IOCthe container, and only the corresponding ones will be configured on demand bean.

Summarize

  • 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/dageliuqing/article/details/127721569