最早接触springboot,给人第一印象的是两个关键点。
其中,四个关键的步骤已标注在图中,分别解释如下
Servlet
或者 webApplicationContext
的一种
SpringFactoriesLoader.loadFactoryNames
查找并加载 classpath下 META-INF/spring.factories
文件中所有可用的 ApplicationContextInitializer
SpringFactoriesLoader.loadFactoryNames
查找并加载 classpath
下 META-INF/spring.factories
文件中的所有可用的 ApplicationListener
这里贴一下寻找的代码:
其实,每次寻找都会全盘加载,然后再选取某一类型的,个人理解,这样会造成多次IO读写,可采用使用map一次IO读取,然后缓存后,多次使用。
各个主要步骤我已经标注在上图之中了,除此之外,我也按照自己的理解画了一个流程图如下所示,可以对照数字标示看一下:
这个获取的时候通过
这个方法,将RunListener类型的类加载进来。
这个在spring .factories
中
打开下面的实现类:
其主要功能,是之前初始化springApplication
时候加载好的listeners
进行调用,这里其实也采用了观察者模式,所有的listeners是观察者,然后主角为 runListener。
循环调用实现类的starting,但是现在spring只有一个实现类,即EveentPublishingRunListener,后续官方可能会有更多实现类。
所以就是调用如下的staring方法:
在这里就是环境准备时候做的东西
会调用
就是上面这里触发调用apollo的初始化工作,为什么这么说,且听我慢慢道来。 首先初始化springApplication的时候加载了很多listener,其中有一个实现类叫做
ConfigFileApplicationListener
在listener调用 onApplicationEvent
的时候 ,会调用ConfigFileApplicationListener
类的onApplicationEvent
方法
注意此loadPostProcessors()
方法,会将所有实现了EnvironmentPostProcessor
接口的类获取。
获取后执行postProcessEnvironment
方法
而apollo的初始化逻辑便放在这里面。
继续之前的 探索:
刷新,完成IoC容器可用的最后一步 !!!
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}