IOC 容器启动入口

建立测试环境

1
2
3
4
5
6
7
8
9
10
public class SpringSourceTest {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("application.xml");

MyService myService = context.getBean(MyService.class);
myService.sayHello();
}
}

application.xml:

1
2
3
4
5
6
7
8
9

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="myService" class="com.example.MyService"/>
</beans>

MyService.java:

1
2
3
4
5
6
public class MyService {
public void sayHello() {
System.out.println("Hello Spring Source!");
}
}

第一个关键类:ClassPathXmlApplicationContext

入口:

1
2
ApplicationContext context =
new ClassPathXmlApplicationContext("application.xml");

构造方法里会调用:

1
this.refresh();

跟源码看 refresh()

refresh() 定义在 AbstractApplicationContext

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
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1. 准备工作
prepareRefresh();

// 2. 获取 BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// 3. BeanFactory 的准备工作
prepareBeanFactory(beanFactory);

// 4. BeanFactory 的后置处理
postProcessBeanFactory(beanFactory);

// 5. 执行 BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);

// 6. 注册 BeanPostProcessor
registerBeanPostProcessors(beanFactory);

// 7. 初始化消息源
initMessageSource();

// 8. 初始化事件广播器
initApplicationEventMulticaster();

// 9. 子类扩展点
onRefresh();

// 10. 注册监听器
registerListeners();

// 11. 实例化所有非懒加载的单例 Bean
finishBeanFactoryInitialization(beanFactory);

// 12. 完成刷新,发布事件
finishRefresh();
}
}