IOC概念

什么是IOC

  • 控制反转:把对象的创建和对象之间的调用过程都交给容器进行管理
  • 使用IOC目的:为了降低代码之间的耦合度

为什么IOC可以降低耦合度

  • 使用原始方式来创建对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface UserDao {
public boolean add();
}

class UserDaoImp implement UserDao{
public boolean add(){
......
}
}

class UserService {
public void execute(){
UserDao dao = new UserDaoImp();
dao.add();
}
}

问题

  1. 如果因为功能扩展或者维护的需求,需要替换UserDao的实现类,那么只能手动修改已有代码,违反了设计模式中的开闭原则
  2. 如果UserDao的实现类被零散的使用到项目的各个模块中,那么对UserDao的实现类的管理成本就会很高
  • 使用工厂模式来创建对象

从上面的例子我们可以看出,使用原始方式来创建对象,会导致代码的耦合度很高,为了降低耦合度,我们可以很容易的想到使用设计模式中的工厂模式来创建对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface UserDao {
public boolean add();
}
class UserDaoImp implement UserDao{
public boolean add(){
......
}
}
class UserFactory {
public static UserDao getDao(){
return new UserDaoImp();
}
}
class UserService {
public void execute(){
UserDao dao = UserFactory.getDao();
dao.add();
}
}


问题

  1. 通过工厂模式创建对象,降低了代码的耦合度、并且对UserDao子类的创建进行集中管理。但是如果需要替换UserDao的实现子类,还是需要修改UserFactory中的源代码,还是违反了开闭原则
  2. 工厂模式只能对一种接口的实现子类进行集中管理,如果项目中存在着许多接口,并且这些接口零散地存在各个模块中,那么工厂模式并不能对这些接口的实现子类进行集中管理
  • 使用IOC来创建对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UserSerice 、UserDao 如上所示

第一步 创建xml配置文件,配置创建对象


第二步 创建工厂类
class UserFactory {
public static UserDao getDao() {
//从xml解析获得
String classValue = UserDao子类的全限定名;
//通过从xml解析获得的UserDao子类的全限定名,来进行反射
Class clazz = Class.forName(classValue);
return (UserDao) clazz.newInstance();
}
}

优点

  1. 通过IOC的方式来创建对象,降低了代码的耦合度,如果后续功能扩展需要替换UserDao的实现子类,只需要修改Xml配置文件,无需修改代码,不会违反开闭原则
  2. 通过xml集中管理项目内的所有接口,便于后续对bean的管理

IOC接口

IOC思想基于IOC容器完成,IOC容器底层就是对象工厂

Spring提供了IOC容器实现两种方式

  1. BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用。
  2. ApplicationContext:BeanFactory接口的子接口,提供更强大的功能,一般由开发人员使用。

BeanFactory和ApplicationContext的区别

  1. BeanFactory: 是懒加载,只有在调用getBean()方法时,才会对容器中的bean进行初始化
  2. ApplicationContext:是预加载,每一个bean都在ApplicationContext启动之后实例化

Spring容器的启动流程

在项目中使用直接实现BeanFactory的容器不多,主要使用的是继承ApplicationContext的容器,因此我们选择ApplicationContext的子类:ClassPathXmlApplicationContext进行分析:

总体启动流程

  1. 创建容器前的准备工作
  2. 先创建beanFactory,加载配置文件,封装成BeanDefinition
  3. beanFactory的准备工作,对beanFactory各种属性进行填充
  4. 调用执行BeanFactoryPostProcessor
  5. 注册beanPostProcessor
  6. 注册各种监听器,事件,广播器
  7. 实例化并初始化配置文件中的bean
  8. 完成上下文的一些刷新工作

refresh方法

Spring IOC源码重点看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
   @Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 创建容器前进行一些准备工作
prepareRefresh();

// 创建beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// 对新创建的beanFactory做一些准备工作,对beanFactory属性进行填充
prepareBeanFactory(beanFactory);

try {
//用于子类覆盖方法,对beanFactory做一些额外处理,增加扩展性
postProcessBeanFactory(beanFactory);

//调用各种beanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);

// 注册bean处理器,这里只是注册功能,还没有真正进行调用,真正进行调用的是getBean方法
registerBeanPostProcessors(beanFactory);

// 为上下文初始化message源,即不同语言的消息体,国际化处理
initMessageSource();

// 初始化事件监听多路广播器
initApplicationEventMulticaster();

// 预留位置给子类初始化其他的bean
onRefresh();

// 在所有注册的bean中查找listerner bean,注册到消息广播器中
registerListeners();

// 初始化剩下的单实例(非懒加载)
finishBeanFactoryInitialization(beanFactory);

// 完成刷新过程,通知生命周期处理器lifecycleProcessor刷新进程,同时发出ContextRefreshEvent通知别人
finishRefresh();
}

}
}

创建容器前的准备工作

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
   protected void prepareRefresh() {
// 设置容器的启动时间
this.startupDate = System.currentTimeMillis();
//设置容器的关闭标志位
this.closed.set(false);
//设置容器的激活标志位
this.active.set(true);
//记录日志
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}

// 初始化属性资源
initPropertySources();

// 创建并获取环境对象,验证需要的环境属性文件是否都已经放入环境中
getEnvironment().validateRequiredProperties();

// 准备监听器和事件的集合对象,默认为空的集合
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}

// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}

创建beanFactory并加载配置文件

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
   protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
//比较简单直接返回已创建的beanFactory
return getBeanFactory();
}

@Override
protected final void refreshBeanFactory() throws BeansException {
//如果存在beanFactory先销毁
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//开始创建beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//为了序列化指定id,可以从id反序列化到beanFactory对象
beanFactory.setSerializationId(getId());
//定制beanFactory,设置相关的属性,包括是否允许覆盖同名称的不同定义的对象以及循环依赖
customizeBeanFactory(beanFactory);
//初始化documentReader,并进行XML文件读取及解析,默认命名空间的解析,自定义标签的解析
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
.....
}
}

beanFactory进行准备工作

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
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//设置类加载器:存在则直接设置/不存在则新建一个默认类加载器
beanFactory.setBeanClassLoader(getClassLoader());

//设置EL表达式解析器(Bean初始化完成后填充属性时会用到)
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

//设置属性注册解析器PropertyEditor
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// 将当前的ApplicationContext对象交给ApplicationContextAwareProcessor类来处理,从而在Aware接口实现类中的注入applicationContext
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

//设置忽略自动装配的接口
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

//注册可以解析的自动装配
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

//如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ,则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入AspectJ的目的。
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}

//注册当前容器环境environment组件Bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}

//注册系统配置systemProperties组件Bean
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}

//注册系统环境systemEnvironment组件Bean
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}

调用执行BeanFactoryPostProcessor

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

// 用来存放已经执行完成的beanFactoryPostProcessor对象
Set processedBeans = new HashSet<>();

if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List regularPostProcessors = new ArrayList<>();
List registryProcessors = new ArrayList<>();

for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}

List currentRegistryProcessors = new ArrayList<>();

// 先执行 实现了 PriorityOrdered接口的 BeanDefinitionRegistryPostProcessors对象的postProcessBeanDefinitionRegistry方法
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}

sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();

// 再执行 实现了 Ordered接口的 BeanDefinitionRegistryPostProcessors 对象的postProcessBeanDefinitionRegistry方法
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();

// 执行剩余的 BeanDefinitionRegistryPostProcessors 对象的postProcessBeanDefinitionRegistry方法
boolean reiterate = true;
// 需要 多加一个循环重复执行剩余的postProcessBeanDefinitionRegistry方法是因为该方法可能注册新的BeanDefinitionRegistryPostProcessors 对象
// 确保每一个BeanDefinitionRegistryPostProcessors 对象的postProcessBeanDefinitionRegistry方法都能被执行到
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}

// 按照之前注册BeanDefinitionRegistryPostProcessors 对象的顺序执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}

else {
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

// 获取所有BeanFactoryPostProcessor对象名称
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// 将BeanFactoryPostProcessor对象分成 priorityOrdered、Ordered、NoneOrdered三个集合
List priorityOrderedPostProcessors = new ArrayList<;>;();
List orderedPostProcessorNames = new ArrayList<>();
List nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// 之前已经执行过了,不再执行
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 先添加priorityOrdered
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 再添加Ordered
orderedPostProcessorNames.add(ppName);
}
else {
// 最后添加既没有实现priorityOrdered也没实现Ordered接口的BeanFactoryPostProcessor对象
nonOrderedPostProcessorNames.add(ppName);
}
}

sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 先执行 实现了 priorityOrdered接口的BeanFactoryPostProcessor对象
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// 再执行 实现了 Ordered接口的BeanFactoryPostProcessor对象
List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// 最后执行既没有实现priorityOrdered也没实现Ordered接口的BeanFactoryPostProcessor对象
List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

beanFactory.clearMetadataCache();
}

注册beanPostProcessor

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
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// 将实现了priorityOrdered接口、Ordered接口、没实现priorityOrdered和Ordered接口的BeanPostProcessor区分开
List priorityOrderedPostProcessors = new ArrayList<>();
List internalPostProcessors = new ArrayList<>();
List orderedPostProcessorNames = new ArrayList<>();
List nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}

// 先对实现了PrirityOrdered接口的BeanPostProcessor进行排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 先注册PrirityOrdered接口的BeanPostProcessor

registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// 再对实现了PrirityOrdered接口的BeanPostProcessor进行注册
List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// 最后注册没有实现 PrirityOrdered接口和Ordered接口的BeanPostProcessor
List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);

// 当实现了ApplicationListener接口的bean创建完成后,将其添加到容器的监听者集合中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}


初始化事件监听多路广播器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 1.判断BeanFactory是否已经存在事件广播器(固定使用beanName=applicationEventMulticaster)
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
// 1.1 如果已经存在,则将该bean赋值给applicationEventMulticaster
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
....
} else {
// 1.2 如果不存在,则使用SimpleApplicationEventMulticaster
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
// 并将SimpleApplicationEventMulticaster作为默认的事件广播器,注册到BeanFactory中
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}

说明

在Spring中,有一些内部的bean会使用固定的beanName,例如事件广播器,固定使用beanName: applicationEventMulticaster

注册监听器

在所有注册的bean中查找listerner bean,注册到消息广播器中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protected void registerListeners() {
// 1.通过硬编码调用addApplicationListener方法添加的监听器处理(可以通过自定义ApplicationContextInitializer添加)
for (ApplicationListener listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}

// 2.通过配置文件或注解注入BeanFactory的监听器处理
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}

// 3.使用事件广播器,发布早期应用程序事件到相应的监听器
Set earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}

主要流程

  1. 通过getApplicationListeners()方法获取到监听器并注册
  2. 通过配置文件或者注解注入获取监听器并注册
  3. 通过事件广播器,将早期的事件发布到已注册的监听器中

完成上下文的一些刷新工作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void finishRefresh() {
// 1.Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();

// 2.为此上下文初始化生命周期处理器
initLifecycleProcessor();

// 3.通知容器中的一些组件进行刷新
getLifecycleProcessor().onRefresh();

// 4.注册上下文刷新完毕事件到相应的监听器
publishEvent(new ContextRefreshedEvent(this));

// 5.Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}

初始化生命周期处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 1.判断BeanFactory是否已经存在生命周期处理器(固定使用beanName=lifecycleProcessor)
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
// 1.1 如果已经存在,则将该bean赋值给lifecycleProcessor
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);

} else {
// 1.2 如果不存在,则使用DefaultLifecycleProcessor
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
// 并将DefaultLifecycleProcessor作为默认的生命周期处理器,注册到BeanFactory中
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);

}
}

流程

优先使用用户自定义的生命周期处理器,如果用户没有自定义就使用默认的DefaultLifecycleProcessor


通知容器中的一些组件进行刷新

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
@Override
public void onRefresh() {
startBeans(true);
this.running = true;
}

private void startBeans(boolean autoStartupOnly) {
// 1.获取所有的Lifecycle bean
Map lifecycleBeans = getLifecycleBeans();
// 2.遍历所有的Lifecycle bean,并按照阶段值进行分组
lifecycleBeans.forEach((beanName, bean) -> {
// autoStartupOnly=true代表是ApplicationContext刷新时容器自动启动 autoStartupOnly=false代表是通过显示的调用启动
// 当autoStartupOnly=false,也就是通过显示的调用启动,会触发全部的Lifecycle
// 当autoStartupOnly=true,也就是ApplicationContext刷新时容器自动启动,只会触发isAutoStartup方法返回true的SmartLifecycle

if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
int phase = getPhase(bean);
LifecycleGroup group = phases.get(phase);
if (group == null) {
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
phases.put(phase, group);
}
group.add(beanName, bean);
}
});

// 3.如果phases不为空 ,则开始调用start方法
if (!phases.isEmpty()) {
List keys = new ArrayList(phases.keySet());

Collections.sort(keys);
for (Integer key : keys) {
phases.get(key).start();
}
}
}

说明

引入了 Phased 接口,这个接口类似于 Ordered 接口,只有一个方法用于返回一个 “阶段值”,范围为 Integer.MIN_VALUE ~Integer.MAX_VALUE。在启动过程,“阶段值” 小的会被优先调用,而在关闭过程,“阶段值” 大的会被优先调用。


注册上下文刷新完毕事件到相应的监听器

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
@Override
public void publishEvent(ApplicationEvent event) {
publishEvent(event, null);
}

protected void publishEvent(Object event, ResolvableType eventType) {


// Decorate event as an ApplicationEvent if necessary
// 1.如有必要,将事件装饰为ApplicationEvent
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
} else {
applicationEvent = new PayloadApplicationEvent(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent) applicationEvent).getResolvableType();
}
}

// 2.立即使用事件广播器广播事件到相应的监听器,或者等事件广播器初始化以后再广播
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
} else {

getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}

// 3.如果存在parent容器,那么通过parent容器发布事件......
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
} else {
this.parent.publishEvent(event);
}
}
}广播器广播事件@Override
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
// 1.getApplicationListeners:返回与给定事件类型匹配的应用监听器集合
for (final ApplicationListener listener : getApplicationListeners(event, type)) {
// 2.返回此广播器的当前任务执行程序
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
@Override
public void run() {
// 3.1 executor不为null,则使用executor调用监听器
invokeListener(listener, event);
}
});
} else {
// 3.2 否则,直接调用监听器
invokeListener(listener, event);
}
}
//1.获得需要发布的事件类型
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
//2.获得用来处理事件的任务执行器
Executor executor = getTaskExecutor();
//3.getApplicationListeners:返回与给定事件类型匹配的应用监听器集合

for (ApplicationListener listener : getApplicationListeners(event, type)) {
if (executor != null) {
executor.execute(() ->; invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}回调事件监听器 protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
//1.获取此广播器的当前错误处理程序
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
doInvokeListener(listener, event);
}
}

//事件监听器真正对事件进行回调
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
//对事件进行回调
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
.....
}
else {
throw ex;
}
}
}