spring | 自动装配
source link: https://benpaodewoniu.github.io/2022/11/08/spring13/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
spring | 自动装配
目前,这里用的 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
方法。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()));
ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).forEach(configurations::add);
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
通过 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
类和其他配置类。
目前,我只能理解到这里,非常肤浅的理解,更深入的可以参考上面的参考资料,后续,随着我的理解深度,我也将持续更新。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK