天天看点

springboot启动流程之bean注册-源码分析(1)

1,断点进入主程序

springboot启动流程之bean注册-源码分析(1)

2,初始化组件

springboot启动流程之bean注册-源码分析(1)

其中实例化组件时,使用反射,如下图示

springboot启动流程之bean注册-源码分析(1)

初始完组建后,

接着是application的run方法

springboot启动流程之bean注册-源码分析(1)

在上面过程中,进入

context = this.createApplicationContext();
           

进入,默认创建一个

AnnotationConfigServletWebServerApplicationContext实例
           
springboot启动流程之bean注册-源码分析(1)

return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);

接着放开断点,继续,

进入this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
           
springboot启动流程之bean注册-源码分析(1)

上面设置context,

跳出后进入this.refreshContext(context);

进入super, AbstractApplicationContext初始化bean,

springboot启动流程之bean注册-源码分析(1)

此时beanmap有7个元素,即以注册了7个beanpostprocessor

springboot启动流程之bean注册-源码分析(1)

而实例对象才3个

springboot启动流程之bean注册-源码分析(1)

接着对于

invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) 
           
springboot启动流程之bean注册-源码分析(1)
springboot启动流程之bean注册-源码分析(1)

进入postprocessor,每个processor注册其他bean

springboot启动流程之bean注册-源码分析(1)

接着走,如下

springboot启动流程之bean注册-源码分析(1)

由于 String[] candidateNames = registry.getBeanDefinitionNames();如上示,一一使用processor注册其他bean,

springboot启动流程之bean注册-源码分析(1)

此时加入了注册启动类bean,为8个,

断点进入如下图示,先注册启动类bean,如下

springboot启动流程之bean注册-源码分析(1)

此展开如下

springboot启动流程之bean注册-源码分析(1)

解析demoapplication时,如下

springboot启动流程之bean注册-源码分析(1)

进入断点

springboot启动流程之bean注册-源码分析(1)

接着进入

springboot启动流程之bean注册-源码分析(1)

往下走

springboot启动流程之bean注册-源码分析(1)

进入此方法,出现CompanScan(重点)

springboot启动流程之bean注册-源码分析(1)

应该是包扫描,寻找待注册的类

springboot启动流程之bean注册-源码分析(1)

进入

springboot启动流程之bean注册-源码分析(1)

进入这个方法最后

springboot启动流程之bean注册-源码分析(1)

开始根据包名,扫描注册

springboot启动流程之bean注册-源码分析(1)

接着看具体实现

springboot启动流程之bean注册-源码分析(1)

出现类的路径模式了

springboot启动流程之bean注册-源码分析(1)

至于如何找到resource数组,暂时流程就是扫描各个包,判断各个.class, 若有Service,controller等注解,说明是candidates,待注入的beandefinitations!!!!,也可以打断点进入,这里不再详述。

看下resource[]数组

springboot启动流程之bean注册-源码分析(1)

,接着循环逐个add即可,首先找到了controller

springboot启动流程之bean注册-源码分析(1)

然后注册controller(add)

springboot启动流程之bean注册-源码分析(1)

后面也有mapper及entity被扫描到并添加z注册到到beandefinitions

springboot启动流程之bean注册-源码分析(1)
springboot启动流程之bean注册-源码分析(1)
springboot启动流程之bean注册-源码分析(1)

这里着重关注下

registerBeanPostProcessors();
           

打断点,进入此方法

springboot启动流程之bean注册-源码分析(1)

默认加载10种beanPostProcessorName,注册并创建对应beanPostProcessor实例,getbean就是创建实例并注册,如下图,

springboot启动流程之bean注册-源码分析(1)

这里注意创建annoautowiredbeanpostprocessor

springboot启动流程之bean注册-源码分析(1)

接着,跳出后

springboot启动流程之bean注册-源码分析(1)
this.onRefresh();
           
springboot启动流程之bean注册-源码分析(1)

对于

createWebServer()
           
springboot启动流程之bean注册-源码分析(1)

接着跳出,

this.finishBeanFactoryInitialization(beanFactory);
           
this.finishRefresh();
           
springboot启动流程之bean注册-源码分析(1)

继续阅读