面试篇SpringBoot自动配置原理是什么

1、SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration。


2、查看@EnableAutoConfiguration,其作用是利用AutoConfigurationlmportSelector给容器中导入一些组件。


3、查看AutoConfigurationlmportSelector,其中public String selectlmports(AnnotationMetadata annotationMetadata)方法内最终调用getCandidateConfigurations()方法


4、查看getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributesattributes),获取候选的配置,这个是扫描所有jar包类路径下"META-INF/spring.factories"


5、然后把扫描到的这些文件包装成Properties对象。


6、从properties中获取到EnableAutoConfiguration.class类名对应的值,然后把他们添加在容器中。


简而言之,整个过程就是将类路径下"META-INF/spring.factories"里面配置的所有EnableAutoConfiguration的值加入到容器中。

经验分享 程序员 微信小程序 职场和发展