ApplicationContext的refresh过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@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.
//获取beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
//对beanFactory进行一些必要的设置
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
//beanFactory的后处理
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
//调用beanFactory的后处理器,扩展点之一
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
//注册bean处理器,扩展点之一
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();
}

catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Destroy already created singletons to avoid dangling resources.
//销毁bean
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}

finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}

可以看到,spring的代码风格,先用方法列出逻辑框架,然后逐一进行填充,值得学习;

后面就每一步进行详细的补充。