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
|
public
void
refresh()
throws
BeansException, IllegalStateException {
synchronized
(
this
.startupShutdownMonitor) {
// 准备上下文用于刷新
prepareRefresh();
// 创建BeanFactory,Bean定义的解析与注册
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 为该上下文配置已经生成的BeanFactory
prepareBeanFactory(beanFactory);
try
{
//可以调用用户自定义的BeanFactory来对已经生成的BeanFactory进行修改
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
//可以对以后再创建Bean实例对象添加一些自定义操作
registerBeanPostProcessors(beanFactory);
//初始化信息源
initMessageSource();
//初始化事件
initApplicationEventMulticaster();
//初始化在特定上下文中的其它特殊Bean
onRefresh();
registerListeners();
//Bean的真正实例化,创建非懒惰性的单例Bean
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
}
catch
(BeansException ex) {
destroyBeans();
cancelRefresh(ex);
throw
ex;
}
}
|
1
2
|
ApplicationContext ctx =
new
ClassPathXmlApplicationContext(
"beans.xml"
);
UserService service = ctx.getBean(
"ser"
,UserService.
class
);
|
1
2
3
4
5
6
7
8
9
10
11
|
public
ClassPathXmlApplicationContext(String[] configLocations,
boolean
refresh, ApplicationContext parent)
{
super
(parent);
//设置配置文件的位置configLocations
setConfigLocations(configLocations);
if
(refresh) {
//这里就是调用了父类AbstractApplicationContext的refresh
//也证实了refresh是构建IOC的入口点
refresh();
}
}
|
1
2
3
4
5
6
7
8
9
10
|
protected
void
loadBeanDefinitions(XmlBeanDefinitionReader reader)
throws
BeansException, IOException {
Resource[] configResources = getConfigResources();
if
(configResources !=
null
) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if
(configLocations !=
null
) {
reader.loadBeanDefinitions(configLocations);
}
}
|
1
2
3
|
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
|