目前,这里用的 spring boot 的版本是 2.7.5,spring boot 在 2.7.0 修改了自动装配的方法。
目前,我对这个的理解很浅薄,只能通过后续慢慢的优化了。
参考资料
基本原理
由 @SpringBootAppliction 组合注解中的 @EnableAutoConfiguration 注解开启自动配置,加载 META-INF/spring/%s.imports 文件中注册的各种 AutoConfiguration 配置类,当其 @Conditional 条件注解生效时,实例化该配置类中定义的 Bean,并注入 Spring 上下文。
2.7.0 之后变更的位置是 org/springframework/boot/spring-boot-autoconfigure/2.7.5/spring-boot-autoconfigure-2.7.5.jar!/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.class 里面的 getCandidateConfigurations 方法。
1 | protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { |
通过 debug 得知第 2 行是装配 2.7.0 之前的 META-INF/spring.factories 的配置类,但是,2.7.0 之后,configurations 执行为空,第 3 行是装配 META-INF/spring/%s.imports 里面的文件,可以发现 configurations 的长度变成了 144。
SpringBoot 自动装配过程涉及以下主要内容:
@EnableAutoConfiguration: 扫描类路径下的META-INF/spring/%s.imports文件,并加载其中中注册的AutoConfiguration配置类,开启自动装配;META-INF/spring/%s.imports:配置文件,位于jar包的META-INF目录下,按照指定格式注册了AutoConfiguration配置类;AutoConfiguration类:自动配置类,SpringBoot的大量以xxxAutoConfiguration命名的自动配置类,定义了三方组件集成Spring所需初始化的Bean和条件;@Conditional条件注解及其行生注解:使用在AutoConfiguration类上,设置了配置类的实例化条件;Starter:三方组件的依赖及配置,包括SpringBoot预置组件和自定义组件,往往会包含spring.factories文件、AutoConfiguration类和其他配置类。
目前,我只能理解到这里,非常肤浅的理解,更深入的可以参考上面的参考资料,后续,随着我的理解深度,我也将持续更新。