上節探討了Spring IOC容器中getBean方法,下面我們將自行編寫測試用例,深入跟蹤分析bean對象創建過程。
測試環境創建
測試示例代碼如下:
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配置文件如下:
<?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代碼如下:
package org.springframework.context.mytests;
public class Worker {
public void work(){
System.out.println("I am working");
}
}
在IDE中對測試文件打斷點,進入Debug模式,一步一步跟隨程序跟蹤bean創建過程。
源碼跟蹤
跟蹤斷點,進入ClassPathXmlApplicationContext源碼,如下所示:
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文件的操作都是在實例化階段完成的。以上是部分源碼片段,在本測試中,調用第一個構造器初始化,但其實質是調用第二個構造器。從源碼可以發現,第二個構造器實際上完成了兩個主要功能:
setConfigLocations(configLocations)
,設置應用上下文的配置文件路徑,如果沒有設置,便會使用默認路徑refresh()
,IOC容器初始化入口
通過查找定位發現:setConfigLocations(configLocations)
是繼承於AbstractRefreshableConfigApplicationContext抽象類,其源碼如下:
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中定義的。其在抽象類中源碼如下:
@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工廠。其源碼如下:
/**
* 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()
,這兩個方法均為抽象方法,如下所示:
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
查找子類發現,這兩個方法均在子類AbstractRefreshableApplicationContext中實現,該類仍然是抽象類。先來看refreshBeanFactory方法實現:
@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
,如下所示:
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
從函數返回值可以看出,重新創建的Bean工廠是默認的bean工廠DefaultListableBeanFactory
類型。創建完新的bean工廠后便會根據上下文進行初始化(customizeBeanFactory),加載bean定義(loadBeanDefinitions)。其中,loadBeanDefinitions為抽象方法,如下所示:
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException;
該方法具體實現在AbstractXmlApplicationContext類中,該類仍然是一個抽象類,實現如下:
@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,具體實現如下:
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中實現就相對簡單寫,如下所示:
@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。