Hello World

吞风吻雨葬落日 欺山赶海踏雪径

0%

spring启动源码分析

spring启动源码分析

初始化的核心流程图
初始化的核心流程图

从上图可知spring的初始化核心逻辑在org.springframework.context.support.AbstractApplicationContext#refresh方法中,调用栈:

1
2
3
4
5
refresh:522, AbstractApplicationContext (org.springframework.context.support)
<init>:197, ClassPathXmlApplicationContext (org.springframework.context.support)
<init>:172, ClassPathXmlApplicationContext (org.springframework.context.support)
<init>:158, ClassPathXmlApplicationContext (org.springframework.context.support)
main:35, Application (com.forg.spring.init)

refresh()方法的核心调用

  1. prepareRefresh();
  2. obtainFreshBeanFactory();
  3. prepareBeanFactory(beanFactory);
  4. postProcessBeanFactory(beanFactory);
  5. invokeBeanFactoryPostProcessors(beanFactory);
  6. registerBeanPostProcessors(beanFactory);
  7. initMessageSource();
  8. initApplicationEventMulticaster();
  9. onRefresh();
  10. registerListeners();
  11. finishBeanFactoryInitialization(beanFactory);
  12. finishRefresh();

下面我们一个一个方法做分析说明

prepareRefresh

方法代码并不长

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 准备刷新,设置应用开启的时间还有active标志,并且执行一些属性源的初始化工作
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);

if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}

// Initialize any placeholder property sources in the context environment
// 初始化placeholder属性
initPropertySources();

// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
// 验证所有的必须的属性
getEnvironment().validateRequiredProperties();

// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 允许应用启动之前的事件,当multicaster一旦可用的时候,可用立刻响应发布的事件
this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

startupDate 记录了context启动的时间。activeclosed分别代表context是否激活与是否已经关闭的标识,他们都是AtomicBoolean类型的。
initPropertySources()初始化了placeholder的属性,默认 do nothing ,方便扩展用的。
validateRequiredProperties()校验了一些必要的属性,org.springframework.core.env.AbstractEnvironment#validateRequiredProperties
随后初始化了earlyApplicationEvents

obtainFreshBeanFactory

创建并获取BeanFactory,此方法逻辑中会将所有配置中Bean的定义封装成BeanDefinition,并加载到新生成的BeanFactory中:

  1. beanDefinitionNames缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 集合。
  2. beanDefinitionMap缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 和 BeanDefinition 映射。
  3. aliasMap缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 和别名映射。
1
2
3
4
5
6
7
8
9
10
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 1.刷新 BeanFactory,由AbstractRefreshableApplicationContext实现
refreshBeanFactory();
// 2.拿到刷新后的 BeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}