springboot相关逻辑
1. main启动类
首先就是springboot项目习以为常的main方法调用SpringApplication.run将标注有@SpringBootApplication注解的class对象作为参数传递。SpringBootApplication注解是个组合注解,主要组合了@Configuration
,@EnableAutoConfiguration
,@Import(AutoConfigurationImportSelector.class)
, @ComponentScan
等关键注解。
@SpringBootApplication
public class SampleWebUiApplication {
public static void main(String[] args) {
SpringApplication.run(SampleWebUiApplication.class, args);
}
}
2. 调用SpringApplication构造函数
通过第一步调用静态方法run,内部转换为实例化SpringApplication并调用实例方法run。
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
/**
* 通过getSpringFactoriesInstances 方法从META-INF/spring.factories文件中获取所有ApplicationContextInitializer 回调接口,
* 用于在刷新之前初始化Spring ConfigurableApplicationContext。
* 通常在需要对应用程序上下文进行一些编程初始化的Web应用程序中使用。
* 例如,注册属性源或针对上下文环境激活配置文件。
* 有关分别声明“ contextInitializerClasses”上下文参数和初始化参数的信息,请参见ContextLoader和FrameworkServlet支持。
* 鼓励ApplicationContextInitializer处理器检测是否已实现Spring的Ordered接口,或者是否存在@Order注释,并在调用之前对实例进行相应的排序。
*/
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
SpringApplication#getSpringFactoriesInstances
从"META-INF/spring.factories"中加载并实例化给定类型的所有实现类
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 使用给定的类加载器从“META-INF/spring.factories”中加载给定类型的所有实现类全限定名。
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 通过反射实例化所有从上面获取的全限定类名
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
3. 调用SpringApplication实例对象的run方法
SpringApplication#run
...... 忽略部分代码
try {
...
// 1. 通过反射实例化ApplicationContext
// 2. 实例化applicationContext时调用其无参构造函数实例化AnnotatedBeanDefinitionReader,ClassPathBeanDefinitionScanner
// 3. 实例化AnnotatedBeanDefinitionReader时构造函数通过AnnotationConfigUtils.registerAnnotationConfigProcessors注册一些内部必要的BeanDefinition
// 如 ConfigurationClassPostProcessor(处理@Configuration @Import等注解), AutowiredAnnotationBeanPostProcessor(自动注入)等。
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[]{ConfigurableApplicationContext.class}, context);
// 1. 调用从spring.factories加载的
// 2. 加载primarySources以及sources到BeanDefinition(用于解析@SpringBootApplication,通过ConfigurationClassPostProcessor)
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 1. 调用AbstractApplicationContext#refresh方法
// 2. 通过调用invokeBeanFactoryPostProcessors方法调用ConfigurationClassPostProcessor处理primarySources类的注解
// 3. ConfigurationClassPostProcessor处理@SpringBootApplication的元注解@ComponentScan扫描包组件注册到BeanDefinitionRegistry
// 4. ConfigurationClassPostProcessor通过@EnableAutoConfiguration的元注解@Import中的AutoConfigurationImportSelector自动导入spring.factories中的类到BeanDefinitionRegistry
// 5.启动内置web容器(调用ServletWebServerApplicationContext#onRefresh)
refreshContext(context);
afterRefresh(context, applicationArguments);
...
} catch (Throwable ex) {
...
}
try {
listeners.running(context);
} catch (Throwable ex) {
...
}
return context;
SpringApplication#createApplicationContext
用于创建ApplicationContext的策略方法,默认情况下,此方法将使用任何明确设置的应用程序上下文或应用程序上下文类,然后再使用合适的默认值。
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
//org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
// org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
// org.springframework.context.annotation.AnnotationConfigApplicationContext
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
} catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
}
}
// 通过反射实例化context,在对应ApplicationContext的构造方法中实例化{@link AnnotatedBeanDefinitionReader
// 并在该reader的构造方法中通过{@link AnnotationConfigUtils#registerAnnotationConfigProcessors}
// 注册一些内部必要的BeanDefinition如:{@link ConfigurationClassPostProcessor},{@link AutowiredAnnotationBeanPostProcessor}等
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
上诉方法最后一步反射实例化应用上下文时,很关键的一步就是向容器中注册一些非常重要的的BeanDefinition(如:ConfigurationClassPostProcessor
,AutowiredAnnotationBeanPostProcessor
等),主要步骤:AnnotationConfigServletWebServerApplicationContext()
-> new AnnotatedBeanDefinitionReader
-> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry)
AnnotationConfigUtils.registerAnnotationConfigProcessors
注册spring内部必要的一些beanDefinition
···
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
// 在Spring#refresh时调用invokeBeanFactoryPostProcessors(beanFactory)方法时调用,用来处理@Configuration @Import等注解
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
// CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
...
下图断点为createApplicationContext
方法执行结束后,beanDefinitionMap中的内容
SpringApplication#prepareContext
准备上下文
...
// 调用从spring.factories获取的ApplicationContextInitializer
applyInitializers(context);
...
// 获取所有资源,如在main方法中传进来的SampleWebUiApplication.class等
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 将资源注册为BeanDefinition
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
下图断点为prepareContext
方法执行结束后,beanDefinitionMap中的内容
SpringApplication#refreshContext
刷新上下文具体如下。
spring refresh之invokeBeanFactoryPostProcessors
调用ConfigurationClassPostProcessor整体流程图
AbstractApplicationContext#refresh
......
// 调用实现BeanFactoryPostProcessor的后置处理器,
// 其实就是在上述new AnnotatedBeanDefinitionReader时注册的解析配置类的后置处理器ConfigurationClassPostProcessor
// 这里主要解析SpringBootApplication元注解中的Import注解以及ComponentScan注解等。
invokeBeanFactoryPostProcessors(beanFactory);
......
AbstractApplicationContext#invokeBeanFactoryPostProcessors
//由于之前注册的都是BeanDefinition,此时还并没有生产任何的BeanFactoryPostProcessor,所以getBeanFactoryPostProcessors是空的
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors
从beanDefinitionMap中获取实现了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口的实现类,并调用
//放置已处理的beanName
Set<String> processedBeans = new HashSet<>();
//放置常规的后置处理器,就是只实现了BeanFactoryPostProcessor接口的
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//放置实现了BeanDefinitionRegistryPostProcessor接口的,之前我们注册的后置处理器中只有ConfigurationClassPostProcessor实现了
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//放置当前的RegistryProcessors
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
//查找实现了BeanDefinitionRegistryPostProcessor接口的BeanName,其实目前就只有一个ConfigurationClassPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//ConfigurationClassPostProcessor同样实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//调用了getBean方法,产生了ConfigurationClassPostProcessor实例,放到currentRegistryProcessors集合中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//将实例化出来的后置处理器放到集合中
registryProcessors.addAll(currentRegistryProcessors);
// 调用ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空,以便处理后面的后置处理器
currentRegistryProcessors.clear();
//再次查找实现了BeanDefinitionRegistryPostProcessor接口的BeanName,这里就是可能就是从配置类中解析出来的一些
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//不包括已经处理过的,并且先处理实现Ordered接口的
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//根据Ordered排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//将后置处理器放到已注册的集合中
registryProcessors.addAll(currentRegistryProcessors);
//调用所有后置处理器的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//再次清理,因为后面还要处理未实现Ordered接口的
currentRegistryProcessors.clear();
......
ConfigurationClassPostProcessor#processConfigBeanDefinitions
处理@Configuration注解以及相关的@Bean,@Import等注解
//放置候选配置类
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
//遍历之前注册的所有bean定义,找到其中的配置类,其实就是我们自己传进来的配置类
for (String beanName : candidateNames) {
//...省略校验过程...
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
//检查是否是有@Configuration注解的BeanDifinition -> full类型的配置类 -> 会把配置类替换成动态代理类
//或者该类包含@Component @ComponentScan @Import @ImportResource @Bean 注解的其中之一 -> lite类型的配置类 -> 不会替换成动态代理类
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
//....省略片段....
//实例化一个配置类解析器
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
do {
//解析配置类
parser.parse(candidates);
parser.validate();
//parser.getConfigurationClasses()就是拿到刚刚解析完放到map中的配置类
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
//这里处理@Import导入的beanDefintion和配置类中的@Bean
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
//以下逻辑是找出未解析的配置类,如@Bean和ImportBeanDefinitionRegistrar所引入的
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
//将是配置类并且没有解析过的BeanDefinition放到候选集合中继续解析
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
ConfigurationClassUtils.checkConfigurationClassCandidate
检查给定的bean定义是否是配置类(或在配置类/组件类中声明的嵌套类,也要自动注册),并进行相应标记。
...
//检查是否有标识@Configuration
Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
//设置配置属性值为full
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
//检查是否包含@Component @ComponentScan @Import @ImportResource @Bean
else if (config != null || isConfigurationCandidate(metadata)) {
//设置配置属性值为lite
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {
return false;
}
经过checkConfigurationClassCandidate
后,此时容器中只有启动类属于配置类,进行解析的只有该类,当然后续还有解析出来的其他配置类会在while里继续解析
ConfigurationClassParser#parse
配置类解析流程
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
// 配置类的beanDefinition为AnnotatedGenericBeanDefinition
if (bd instanceof AnnotatedBeanDefinition) {
//传入配置类的元数据与beanName
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
......
}
// 处理实现了DeferredImportSelector接口的实现类,用来延迟处理@Import
// @EnableAutoConfiguration注解导入的AutoConfigurationImportSelector就属于该类型
this.deferredImportSelectorHandler.process()
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
}
ConfigurationClassParser#processConfigurationClass
...
SourceClass sourceClass = asSourceClass(configClass, filter);
do {
//解析配置类,这里可能返回配置类的父类,需要继续处理
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
//将配置类放入map中
this.configurationClasses.put(configClass, configClass);
ConfigurationClassParser#doProcessConfigurationClass
......
//@Configuration 本身也是 @Component的组合注解
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// 处理内置类,如果内置类也是个配置类,递归处理内置类
processMemberClasses(configClass, sourceClass, filter);
}
// Process any @ComponentScan annotations
// 找出配置类上的@ComponentScan注解属性
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
for (AnnotationAttributes componentScan : componentScans) {
//将@ComponentScan引入的所有类扫描成BeanDefinition并注册到容器中
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
//这里循环是为了判断扫描出来的beanDefinition是否是配置类,如果是配置类的话需要递归解析
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
//这里是必然为true, 能被扫描出来的必然有@Component注解,而@Component注解为lite配置类
//这里主要是为了在检查的同时设置一下full或者lite的类型
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
//配置类就继续递归解析
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
// 处理@Import注解
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
...
// 将配置类中@Bean的方法解析成方法元数据放到配置类中
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
...
ConfigurationClassParser#processImports
处理@Import注解
//importCandidates为@Import中的value数组
for (SourceClass candidate : importCandidates) {
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
//实例化我们写的实现ImportSelector接口的类
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
this.environment, this.resourceLoader, this.registry);
if (selector instanceof DeferredImportSelector) {
// 如果是实现了延迟导入,则用延迟导入方式导入
// 将其加入到deferredImportSelectors数组中,待全部处理完后在ConfigurationClassParser#parse方法最后进行处理导入
// @EnableAutoConfiguration注解导入的AutoConfigurationImportSelector就属于该类型
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
} else {
//调用selectImports方法返回我们需要注入到容器中bean数组
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
//转为SourceClass集合
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
//再次递归调用本方法,如果我们返回的数组是一些没有实现Import相关接口的类,
//就会走到最后的else逻辑,当成配置类处理
processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
}
}
//这里就走实现ImportBeanDefinitionRegistrar接口的逻辑
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
//实例化
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
//这里先把Registrar放到配置类的importBeanDefinitionRegistrars属性中,最后解析完调用loadBeanDefinition进行处理
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
//普通的bean当做配置类处理
processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
}
}
处理完上述方法后回到ConfigurationClassParser#parse
的最后一步处理DeferredImportSelector接口实现类(this.deferredImportSelectorHandler.process()
),调用ConfigurationClassParser.DeferredImportSelectorGroupingHandler#processGroupImports
ConfigurationClassParser.DeferredImportSelectorGrouping#getImports
获取DeferredImportSelector导入的条目
for (DeferredImportSelectorHolder deferredImport : this.deferredImports {
// 调用AutoConfigurationImportSelector.AutoConfigurationGroup#process获取需要自动导入的配置类
this.group.process(deferredImport.getConfigurationClass().getMetadata(),
deferredImport.getImportSelector());
}
return this.group.selectImports();
AutoConfigurationImportSelector.AutoConfigurationGroup#process
获取需要自动导入的配置类信息
// 从META-INFO/spring.factories文件下获取EnableAutoConfiguration对应的配置类列表
AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
.getAutoConfigurationEntry(annotationMetadata);
this.autoConfigurationEntries.add(autoConfigurationEntry);
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
this.entries.putIfAbsent(importClassName, annotationMetadata);
}
AutoConfigurationImportSelector#getAutoConfigurationEntry
...
// 从META-INFO/spring.factories文件下获取EnableAutoConfiguration对应的配置类列表
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
// 从META-INFO/spring.factories文件下获取org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的配置类列表
// getSpringFactoriesLoaderFactoryClass() -> EnableAutoConfiguration.class
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;
}
执行完getCandidateConfigurations获取到的配置列表
最后回到ConfigurationClassPostProcessor#processConfigBeanDefinitions
方法中的的this.reader.loadBeanDefinitions(configClasses)
将解析出来的类注册到beanDefinitionMap,之后在refresh的finishBeanFactoryInitialization
方法中实例化这些bean。