自动装配原理
https://juejin.cn/post/7333937659838562356?searchId=20240228230745DB6AB2EEC09EFAA1B090
# 自动装配原理
# @SpringBootAplication
@EnableAutoConfiguration
:启用 SpringBoot 的自动配置机制;@Configuration
:允许在上下文中注册额外的 bean 或导入其他配置类;@ComponentScan
:扫描被@Component
(@Service
,@Controller
)注解的 bean;
# @EnableAutoConfiguration
核心功能的实现实际是通过
AutoConfigurationImportSelector
类;@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage //作用:将main包下的所有组件注册到容器中 @Import({AutoConfigurationImportSelector.class}) //加载自动装配类 xxxAutoconfiguration public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; }
1
2
3
4
5
6
7
8
9
10
11
12
13
# AutoConfigurationImportSelector
实现了ImportSelector接口,实现了它的selectImports方法,用于获取符合条件的类全限定名,加载到IOC容器中;
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered { } public interface DeferredImportSelector extends ImportSelector { } public interface ImportSelector { String[] selectImports(AnnotationMetadata var1); }
1
2
3
4
5
6
7
8
9
10
11public String[] selectImports(AnnotationMetadata annotationMetadata) { // <1>.判断自动装配开关是否打开 if (!this.isEnabled(annotationMetadata)) { return NO_IMPORTS; } else { //<2>.获取所有需要装配的bean AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader); AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata); return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations()); } } }
1
2
3
4
5
6
7
8
9
10
11
12
# getAutoConfigurationEntry()
可以从META-INF/spring.factories加载自动配置类;