前言 :
至今做了几年码农, 辞职后 接近着开始找工作,面试, 在我印象中最深刻的就是,XXX公司问我springboot实现原理及优势
坑坑巴巴的说了一下. 已自闭~
[面试官: 今天就到这里吧. 回去等通知!]
一首凉凉送给自己
回去后,阅读了下源码. 才恍然大悟.
可以参考下 官方文
之前需要我们自己装载, 之后springboot简化了这些
室友的呼噜声好大~ 哈哈哈
- 先从启动类开始
- @SpringBootApplication 做了些什么
- SpringApplication.run 干了什么
- 点进去 可以看到如下
- @EnableAutoConfiguration
- @SpringBootConfiguration
@SpringBootConfiguration // 此注解 源码中引用了@Configuration 配置
@EnableAutoConfiguration // 自动配置
- 自动配置
@EnableAutoConfiguration
-
@AutoConfigurationPackage 自动配置包
导入了选择器 -
选择组件
- 加载源数据
static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader) {
return loadMetadata(classLoader, PATH);
}
static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader, String path) {
try {
Enumeration<URL> urls = (classLoader != null) ? classLoader.getResources(path)
: ClassLoader.getSystemResources(path);
Properties properties = new Properties();
while (urls.hasMoreElements()) {
properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement())));
}
return loadMetadata(properties);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex);
}
}
- getAutoConfigurationEntry 自动配置实体
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationMetadata);
// getCandidateConfigurations 获取所有配置
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
- 获取候选配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
// spring工厂加载
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
// 断言 非空, 如果不为空 就会加载spring.factories 配置文件
例如: redis 自动配置 ,放入了容器中
@ConditionalOnClass(RedisOperations.class) 条件成立后会加载,不成立不会导入对应的jar
- 当前了类的classLoader
标注了: 是谁使用了 @EnableAutoConfiguration
启动类启用了自动配置 自动导入了
此致