利用@Import注解加载bean的机制,实现了SpringBoot的自动配置,@Import注解可用ImportSelector这个接口加载相应类型的Bean。
详细原理边看代码边说,另外提前注明,此处用的SpringBoot版本较老,2.1的,后来本人在2.7的版本再看,除了META-INF下的spring.factories文件,还引用了spring目录下的.imports文件;而到了3.0版本后,不再使用spring.factories文件,自动配置类全部从.imports文件中读取了,不过原理类似,这里不再赘述。

起手SpringBootApplication启动类,上面有个@EnableAutoConfiguration注解,点进去:

@Import(AutoConfigurationImportSelector.class),点进去AutoConfigurationImportSelector:

AutoConfigurationImportSelector实现了DeferredImportSelector接口,而DeferredImportSelector接口继承了ImportSelector接口,ImportSelector接口里有一个selectImports方法,这个方法返回需要用@Import注解引入Spring容器的Bean的类全限定名,AutoConf

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



