How does springboot realize automatic configuration through annotations

SpringBootApplicationThe source code is as follows:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
    
     @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    
    }

The note related to automatic configuration is @EnableAutoConfigurationthat the source code is as follows:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    
    }

First look @AutoConfigurationPackage, the source code of the annotation is as follows:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
    
    

}

By @Import(AutoConfigurationPackages.Registrar.class)introducing the package path where the startup class is located, it is mainly used by subsequent frameworks, such as JPA, etc. The debug is as follows:

org.springframework.boot.autoconfigure.AutoConfigurationPackages#register
public static void register(BeanDefinitionRegistry registry, String... packageNames) {
    
    
	if (registry.containsBeanDefinition(BEAN)) {
    
    
		BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
		ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
		constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));
	}
	else {
    
    
		GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
		beanDefinition.setBeanClass(BasePackages.class);
		beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);
		beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		registry.registerBeanDefinition(BEAN, beanDefinition);
	}
}

Insert picture description here
The annotation @Import(AutoConfigurationImportSelector.class)is to introduce the required automatic configuration, debug is as follows:

org.springframework.context.annotation.ConfigurationClassParser.DeferredImportSelectorGrouping#getImports
public Iterable<Group.Entry> getImports() {
    
    
	for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
    
    
		this.group.process(deferredImport.getConfigurationClass().getMetadata(),
				deferredImport.getImportSelector());
	}
	return this.group.selectImports();
}

Insert picture description here

Guess you like

Origin blog.csdn.net/wang0907/article/details/113463404