产生的背景:
spring boot之前,使用ssh或者ssm等框架开发,需要繁多的配置文件,开发效率较低,部署运维也较为麻烦,这时候为了解决这些问题spring boot 就应运而生了。
官网简介: Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
主要阐述和记录spring boot 的核心功能,底部附官网链接:
- 一个可以独立运行的spring 项目
- 内嵌了Servlet容器
- 提供大量的starter 简化maven配置
- 自动配置spring,根据引入的maven包(jar包),为里面的类自动配置bean(大部分,并不是所有)
- 提供了准生产的应用监控
- 无代码生成和xml配置,通过条件注解来实现
总结:
1-3、5是为了简化开发流程做的封装和优化,4和6为其核心特色
简述总流程:启动,扫描所有含有 META-INF/spring.factories 的jar包,根据这个文件加载配置类,根据配置类加载满足条件的bean。
源码阅读和分析:
- SpringBootApplication 注解:
- 核心启动注解,为组合注解
- 通过EnableAutoConfiguration 实现根据引入了哪些jar包自动配置
- @AutoConfigurationPackage
- @Import({AutoConfigurationImportSelector.class})
- AutoConfigurationImportSelector 这个类是动态引入
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
public static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader) {
return loadMetadata(classLoader, "META-INF/spring-autoconfigure-metadata.properties");
}
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}
- starter 模块原理:
- 最浅显的为,封装了某个功能所有的相关依赖包和对应的版本号
- 封装好的starter模块如何需要添加默认配置,这时候要参考上一个知识点了
- META-INF/spring-autoconfigure-metadata.properties
- META-INF/spring.factories
如果对bean的生成有疑惑:
参考地址: