Spring IOC容器分析(4) -- bean创建获取完整流程

上节探讨了Spring IOC容器中getBean方法,下面我们将自行编写测试用例,深入跟踪分析bean对象创建过程。

测试环境创建

测试示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package org.springframework.context.mytests;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicationContextTest {
@Test
public void testApplicationContext() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("numbers: " + applicationContext.getBeanDefinitionCount());
((Worker)applicationContext.getBean("worker")).work();
}
}

应用ClassPathXmlApplicationContext加载解析xml文件,xml配置文件如下:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="worker" class="org.springframework.context.mytests.Worker"></bean>
</beans>

bean Worker代码如下:

1
2
3
4
5
6
7
package org.springframework.context.mytests;
public class Worker {
public void work(){
System.out.println("I am working");
}
}

在IDE中对测试文件打断点,进入Debug模式,一步一步跟随程序跟踪bean创建过程。

源码跟踪

跟踪断点,进入ClassPathXmlApplicationContext源码,如下所示:

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
package org.springframework.context.support;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
......
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
......
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
......
}

ClassPathXmlApplicationContex中都是构造器方法,表明加载解析xml文件的操作都是在实例化阶段完成的。以上是部分源码片段,在本测试中,调用第一个构造器初始化,但其实质是调用第二个构造器。从源码可以发现,第二个构造器实际上完成了两个主要功能:

  1. setConfigLocations(configLocations),设置应用上下文的配置文件路径,如果没有设置,便会使用默认路径
  2. refresh(),IOC容器初始化入口

通过查找定位发现:setConfigLocations(configLocations)是继承于AbstractRefreshableConfigApplicationContext抽象类,其源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}

可以看到setConfigLocations方法获取定位信息首先需要调用resolvePath方法对路径进行预处理。

refresh方法是继承于AbstractApplicationContext抽象类,是在接口ConfigurableApplicationContext中定义的。其在抽象类中源码如下:

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
@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.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
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.
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();
}
}
}

refresh方法大致描述了Spring IOC容器的初始化过程,第一步prepareRefresh主要是做一些准备工作,如准备应用环境、设置启动时间、设置属性源初始化标志等。重点看第二步ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(),这一步是获取更新后的子类Bean工厂。其源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}

其内部有两个方法refreshBeanFactory()getBeanFactory(),这两个方法均为抽象方法,如下所示:

1
2
3
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

查找子类发现,这两个方法均在子类AbstractRefreshableApplicationContext中实现,该类仍然是抽象类。先来看refreshBeanFactory方法实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

该方法先判断是否存在BeanFactory,若存在则直接销毁原BeanFactory,先销毁工厂中的Beans,再关闭工bean厂。之后创建新的Bean工厂,其方法为createBeanFactory,如下所示:

1
2
3
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

从函数返回值可以看出,重新创建的Bean工厂是默认的bean工厂DefaultListableBeanFactory类型。创建完新的bean工厂后便会根据上下文进行初始化(customizeBeanFactory),加载bean定义(loadBeanDefinitions)。其中,loadBeanDefinitions为抽象方法,如下所示:

1
2
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException;

该方法具体实现在AbstractXmlApplicationContext类中,该类仍然是一个抽象类,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}

阅读源码发现,方法内部是采用XmlBeanDefinitionReader来读取加载bean对象。通过追踪源码,发现XmlBeanDefinitionReader最终调用loadBeanDefinitions方法来读取加载bean,具体实现如下:

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
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}

到此,应该明白了IOC容器初始化bean工厂、加载bean对象的大致过程了。现在回头再来看obtainFreshBeanFactory方法中的另一个方法getBeanFactory方法。该方法在子类AbstractRefreshableApplicationContext中实现就相对简单写,如下所示:

1
2
3
4
5
6
7
8
9
10
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}

到此为止,Spring IOC容器加载机制探讨基本上告一段落了。通过对源码分析,对Spring IOC机制能有一个大致的了解:1、解析、定位、加载xml配置文件;2、提取配置文件内容;3、新建bean工厂;4、创建Bean定义,并放入map中存储。通过追踪源码,也深刻体会到了spring对设计模式的应用。

下一节将进入对Spring另一大杀器的探讨,Spring-AOP