zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【SpringBoot】自动装配原理

2023-06-13 09:17:13 时间

什么是自动装配?

自动装配就是把别人(官方)写好的config配置类加载到spring容器中 然后根据这个配置类生成一些

项目需要的bean对象(没学习Springboot的时候 配置类都要手写 springboot都是别人写好 不用管)

原理

1.在启动类加上关键字@SpringBootApplication 它是个复合注解

2.忽略元注解 主要注解有三个 

@SpringBootConfiguration 

@EnableAutoConfiguration(核心注解)

@ComponentScan

 点击SpringbootConfiguration 可以看到@Configuration标记启动类 为一个配置类

接着我们看看@ComponentScan 它主要是扫描包下的@Component(@Service、@Controller、

@Mapper)等这些注解 将他们添加到spring容器中

最后是springboot的核心注解@EnableAutoConfiguration 启动springboot自动装配机制 有两个核心

注解 @AutoConfigurationPackage扫描main下面的第三方注解 加载到spring容器 @Import导入了

一个AutoConfigurationImportSelector类 这是springboot自动装配的核心类

 AutoConfigurationImportSelector实现了DeferredImportSelector接口而DeferredImportSelector又

继承了ImportSelector接口 在ImportSelector接口中有个selectImports方法

 AutoConfigurationImportSelector 对它进行了重写

 ​​​​​​​

AutoConfigurationImportSelector重写selectImports方法 取所有符合条件的类的全限定类名,这些

类需要被加载到 IoC 容器中 重点关注一下selectImports的getAutoConfigurationEntry,这个方法

主要负责加载自动配置类的。

 在getAutoConfigurationEntry的getCandidateConfigurations方法中获取需要自动装配的所有配置

类,读取META-INF/spring.factories

这样spring.factories的配置类就会读取到spring容器中