spring最核心的理念是IOC,包括AOP也要屈居第二,那么IOC到底是什么呢,四個字,控制反轉
一、什么是Ioc/DI?
IoC 容器:最主要是完成了完成對象的創建和依賴的管理注入等等。
先從我們自己設計這樣一個視角來考慮:
所謂控制反轉,就是把原先我們代碼里面需要實現的對象創建、依賴的代碼,反轉給容器來幫忙實現。那么必然的我們需要創建一個容器,同時需要一種描述來讓容器知道需要創建的對象與對象的關系。這個描述最具體表現就是我們可配置的文件。
對象和對象關系怎么表示?
可以用 xml , properties 文件等語義化配置文件表示。
描述對象關系的文件存放在哪里?
可能是 classpath , filesystem ,或者是 URL 網絡資源, servletContext 等。
回到正題,有了配置文件,還需要對配置文件解析。
不同的配置文件對對象的描述不一樣,如標准的,自定義聲明式的,如何統一? 在內部需要有一個統一的關於對象的定義,所有外部的描述都必須轉化成統一的描述定義。
如何對不同的配置文件進行解析?需要對不同的配置文件語法,采用不同的解析器
二、 Spring IOC體系結構?
(1) BeanFactory
Spring Bean的創建是典型的工廠模式,這一系列的Bean工廠,也即IOC容器為開發者管理對象間的依賴關系提供了很多便利和基礎服務。
首先是BeanFactory ,它會根據定義好的不同的依賴選擇不同的設計模式(主要有單例和原型模式)來返回bean,他們有不同的作用域,spring 2.0以后,作用域更加復雜。

1 public interface BeanFactory {
2
3 //對FactoryBean的轉義定義,因為如果使用bean的名字是一個factoryBean那么返回就是一個factory
5 String FACTORY_BEAN_PREFIX = "&";
6
7 //根據bean的名字,獲取在IOC容器中得到bean實例
8 Object getBean(String name) throws BeansException;
9
10 //根據bean的名字和Class類型來得到bean實例,增加了類型安全驗證機制。
11 Object getBean(String name, Class requiredType) throws BeansException;
12
13 //提供對bean的檢索,看看是否在IOC容器有這個名字的bean
14 boolean containsBean(String name);
15
16 //根據bean名字得到bean實例,並同時判斷這個bean是不是單例
17 boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
18
19 //得到bean實例的Class類型
20 Class getType(String name) throws NoSuchBeanDefinitionException;
21
22 //得到bean的別名,如果根據別名檢索,那么其原名也會被檢索出來
23 String[] getAliases(String name);
24
}
在Spring中有許多的IOC容器的實現供用戶選擇和使用,其相互關系如下:

其中BeanFactory作為最頂層的一個接口類,它定義了IOC容器的基本功能規范,BeanFactory 有三個子類:ListableBeanFactory、HierarchicalBeanFactory 和AutowireCapableBeanFactory。但是從上圖中我們可以發現最終的默認實現類是 DefaultListableBeanFactory,他實現了所有的接口。那為何要定義這么多層次的接口呢?查閱這些接口的源碼和說明發現,每個接口都有他使用的場合,它主要是為了區分在 Spring 內部在操作過程中對象的傳遞和轉化過程中,對對象的數據訪問所做的限制。例如 ListableBeanFactory 接口表示這些 Bean 是可列表的,而 HierarchicalBeanFactory 表示的是這些 Bean 是有繼承關系的,也就是每個Bean 有可能有父 Bean。AutowireCapableBeanFactory 接口定義 Bean 的自動裝配規則。這四個接口共同定義了 Bean 的集合、Bean 之間的關系、以及 Bean 行為.
這個類BeanFactory是spring中所有bean工廠,也就是俗稱的IOC容器的祖先,各種IOC容器都只是它的實現或者為了滿足特別需求的擴展實現,包括我們平時用的最多的ApplicationContext。從上面的方法就可以看出,這些工廠的實現最大的作用就是根據bean的名稱亦或類型等等,來返回一個bean的實例。
一個工廠如果想擁有這樣的功能,那么它一定需要以下幾個因素:
1.需要持有各種bean的定義,否則無法正確的完成bean的實例化。
2.需要持有bean之間的依賴關系,否則在bean實例化的過程中也會出現問題。例如上例,如果我們只是各自持有Person和Company,卻不知道他們的依賴關系,那么在Company初始化以后,調用open方法時,就會報空指針。這是因為Company其實並沒有真正的被正確初始化。
3.以上兩種都要依賴於我們所寫的依賴關系的定義,暫且認為是XML文件(其實可以是各種各樣的),那么我們需要一個工具來完成XML文件的讀取。
我目前想到的,只需要滿足以上三種條件,便可以創建一個bean工廠,來生產各種bean。當然,spring有更高級的做法,以上只是我們直觀的去想如何實現IOC。
其實在上述過程中仍舊有一些問題,比如第一步,我們需要持有bean的定義,如何持有?這是一個問題。我們知道spring的XML配置文件中,有一個屬性是lazy-init,這就說明,bean在何時實例化我們是可以控制的。這個屬性默認是false,但是我們可以將這個屬性設置為true,也就是說spring容器初始化以后,配置了延遲加載的各種bean都還未產生,它們只在需要的時候出現。
所以我們無法直接的創建一個Map<String,Object>來持有這些bean的實例,在這里要注意,我們要儲存的是bean的定義,而非實例。
那么接下來,又是一個祖宗級別的接口要出現了,來看BeanDefinition。
(2) BeanDefinition
這個便是spring中的bean定義接口,所以其實我們工廠里持有的bean定義,就是一堆這個玩意,或者是他的實現類和子接口。這個接口並非直接的祖宗接口,他所繼承的兩個接口一個是core下面的AttributeAccessor,繼承這個接口就以為這我們的bean定義接口同樣具有處理屬性的能力,而另外一個是beans下面的BeanMetadataElement,字面翻譯這個接口就是bean的元數據元素,它可以獲得bean的配置定義的一個元素。在XML文件中來說,就是會持有一個bean標簽。

package org.springframework.beans.factory.config; import org.springframework.beans.BeanMetadataElement; import org.springframework.beans.MutablePropertyValues; import org.springframework.core.AttributeAccessor; public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement { String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON; String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE; int ROLE_APPLICATION = 0; int ROLE_SUPPORT = 1; int ROLE_INFRASTRUCTURE = 2; String getParentName(); void setParentName(String parentName); String getBeanClassName(); void setBeanClassName(String beanClassName); String getFactoryBeanName(); void setFactoryBeanName(String factoryBeanName); String getFactoryMethodName(); void setFactoryMethodName(String factoryMethodName); String getScope(); void setScope(String scope); boolean isLazyInit(); void setLazyInit(boolean lazyInit); String[] getDependsOn(); void setDependsOn(String[] dependsOn); boolean isAutowireCandidate(); void setAutowireCandidate(boolean autowireCandidate); boolean isPrimary(); void setPrimary(boolean primary); ConstructorArgumentValues getConstructorArgumentValues(); MutablePropertyValues getPropertyValues(); boolean isSingleton(); boolean isPrototype(); boolean isAbstract(); int getRole(); String getDescription(); String getResourceDescription(); BeanDefinition getOriginatingBeanDefinition(); } 復制代碼
仔細觀看,能發現beanDefinition中有兩個方法分別是String[] getDependsOn()和void setDependsOn(String[] dependsOn),這兩個方法就是獲取依賴的beanName和設置依賴的beanName,這樣就好辦了,只要我們有一個BeanDefinition,就可以完全的產生一個完整的bean實例。
那么知道了上述兩個接口,我相信不少人甚至不看源碼都已經猜到spring是如何做的了。沒錯,就是讓bean工廠持有一個Map<String,BeanDefinition>,這樣就可以在任何時候我們想用哪個bean,取到它的bean定義,我們就可以創造出一個新鮮的實例。
接口當然不可能持有這樣一個對象,那么這個對象一定是在BeanFactory的某個實現類或者抽象實現類當中所持有的,上面我們說了BeanFactory的繼承關系,我們發現最終的默認實現類是 DefaultListableBeanFactory。
(3)DefaultListableBeanFactory
它的源碼為:
package org.springframework.beans.factory.support;
/**
* Default implementation of the
* based on bean definition objects.
*
* <p>Can be used as a standalone bean factory, or as a superclass for custom
* bean factories. Note that readers for specific bean definition formats are
* typically implemented separately rather than as bean factory subclasses:.
*
*/
@SuppressWarnings("serial")
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
private static Class<?> javaxInjectProviderClass = null;
static {
ClassLoader cl = DefaultListableBeanFactory.class.getClassLoader();
try {
javaxInjectProviderClass = cl.loadClass("javax.inject.Provider");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - Provider interface simply not supported then.
}
}
/** Map from serialized id to factory instance */
private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
new ConcurrentHashMap<String, Reference<DefaultListableBeanFactory>>(8);
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(64);
/** Map of singleton and non-singleton bean names keyed by dependency type */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<Class<?>, String[]>(64);
/** Map of singleton-only bean names keyed by dependency type */
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<Class<?>, String[]>(64);
/** List of bean definition names, in registration order */
private final List<String> beanDefinitionNames = new ArrayList<String>();
/**
* Create a new DefaultListableBeanFactory.
*/
public DefaultListableBeanFactory() {
super();
}
/**
* Create a new DefaultListableBeanFactory with the given parent.
* @param parentBeanFactory the parent BeanFactory
*/
public DefaultListableBeanFactory(BeanFactory parentBeanFactory) {
super(parentBeanFactory);
}
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface
//---------------------------------------------------------------------
public <T> T getBean(Class<T> requiredType) throws BeansException {
Assert.notNull(requiredType, "Required type must not be null");
String[] beanNames = getBeanNamesForType(requiredType);
if (beanNames.length > 1) {
ArrayList<String> autowireCandidates = new ArrayList<String>();
for (String beanName : beanNames) {
if (getBeanDefinition(beanName).isAutowireCandidate()) {
autowireCandidates.add(beanName);
}
}
if (autowireCandidates.size() > 0) {
beanNames = autowireCandidates.toArray(new String[autowireCandidates.size()]);
}
}
if (beanNames.length == 1) {
return getBean(beanNames[0], requiredType);
}
else if (beanNames.length > 1) {
T primaryBean = null;
for (String beanName : beanNames) {
T beanInstance = getBean(beanName, requiredType);
if (isPrimary(beanName, beanInstance)) {
if (primaryBean != null) {
throw new NoUniqueBeanDefinitionException(requiredType, beanNames.length,
"more than one 'primary' bean found of required type: " + Arrays.asList(beanNames));
}
primaryBean = beanInstance;
}
}
if (primaryBean != null) {
return primaryBean;
}
throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
}
else if (getParentBeanFactory() != null) {
return getParentBeanFactory().getBean(requiredType);
}
else {
throw new NoSuchBeanDefinitionException(requiredType);
}
}
}
其中
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
讓bean工廠持有一個Map<String,BeanDefinition>,這樣就可以在任何時候我們想用哪個bean,取到它的bean定義,我們就可以創造出一個新鮮的實例。
那么從現在來看,我們需要什么才能把Map填充呢?也就是初始化bean工廠呢,或者說建立IOC容器。我首先列出來以下幾步。
1.需要一個File指向我們的XML文件(本文的配置文件都已XML為例,因為這是我們最熟悉的),專業點可以叫資源定位,簡單點可以說我們需要一些工具來完成找到XML文件的所在位置。
2.需要一個Reader來讀取我們的XML文件,專業點叫DOM解析,簡單點說,就是把XML文件的各種定義都給拿出來。
3.需要將讀出來的數據都設置到Map當中。
那么從現在來看,我們需要什么才能把Map填充呢?也就是初始化bean工廠呢,或者說建立IOC容器。
1.需要一個File指向我們的XML文件(本文的配置文件都已XML為例,因為這是我們最熟悉的),專業點可以叫資源定位,簡單點可以說我們需要一些工具來完成找到XML文件的所在位置。
2.需要一個Reader來讀取我們的XML文件,專業點叫DOM解析,簡單點說,就是把XML文件的各種定義都給拿出來。
3.需要將讀出來的數據都設置到Map當中。
這三步總結起來就是定位、解析、注冊。
(4)定位、解析、注冊
spring提供了許多IOC容器的實現。比如XmlBeanFactory,ClasspathXmlApplicationContext等。其中XmlBeanFactory就是針對最基本的ioc容器的實現,這個IOC容器可以讀取XML文件定義的BeanDefinition(XML文件中對bean的描述),如果說XmlBeanFactory是容器中的屌絲,ApplicationContext應該算容器中的高帥富.
XmlBeanFactory源碼如下:
package org.springframework.beans.factory.xml; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.Resource; /** * Convenience extension of {@link DefaultListableBeanFactory} that reads bean definitions * from an XML document. Delegates to {@link XmlBeanDefinitionReader} underneath; effectively * equivalent to using an XmlBeanDefinitionReader with a DefaultListableBeanFactory. * * <p>The structure, element and attribute names of the required XML document * are hard-coded in this class. (Of course a transform could be run if necessary * to produce this format). "beans" doesn't need to be the root element of the XML * document: This class will parse all bean definition elements in the XML file.*/ @Deprecated @SuppressWarnings({"serial", "all"}) public class XmlBeanFactory extends DefaultListableBeanFactory { private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this); /** * Create a new XmlBeanFactory with the given resource, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @throws BeansException in case of loading or parsing errors */ public XmlBeanFactory(Resource resource) throws BeansException { this(resource, null); } /** * Create a new XmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @throws BeansException in case of loading or parsing errors */ public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException { super(parentBeanFactory); this.reader.loadBeanDefinitions(resource); } }
直接上代碼,我們還使用Person類作為一個Bean。
package com.springframework.beans.test; public class Person { public void work(){ System.out.println("I am working"); } }
我們還需要寫一個簡單的XML文件,beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="person" class="com.springframework.beans.test.Person"></bean> </beans>
下面是我們根據上述的思路寫一段程序。
package com.springframework.beans.test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; public class TestDefaultListableBeanFactory { public static void main(String[] args) { ClassPathResource classPathResource = new ClassPathResource("beans.xml"); DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(defaultListableBeanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(classPathResource); System.out.println("numbers: " + defaultListableBeanFactory.getBeanDefinitionCount()); ((Person)defaultListableBeanFactory.getBean("person")).work(); } }
對於xmlbeanfactory,代碼為:
//根據Xml配置文件創建Resource資源對象,該對象中包含了BeanDefinition的信息 ClassPathResource resource =new ClassPathResource("application-context.xml"); //創建DefaultListableBeanFactory DefaultListableBeanFactory factory =new DefaultListableBeanFactory(); //創建XmlBeanDefinitionReader讀取器,用於載入BeanDefinition。之所以需要BeanFactory作為參數,是因為會將讀取的信息回調配置給factory XmlBeanDefinitionReader reader =new XmlBeanDefinitionReader(factory); //XmlBeanDefinitionReader執行載入BeanDefinition的方法,最后會完成Bean的載入和注冊。完成后Bean就成功的放置到IOC容器當中,以后我們就可以從中取得Bean來使用 reader.loadBeanDefinitions(resource);
第一行完成了我們的第一步,即資源定位,采用classpath定位,因為我的beans.xml文件是放在src下面的。
第二行創建了一個默認的bean工廠。
第三行創建了一個reader,從名字就不難看出,這個reader是用來讀取XML文件的。這一步要多說一句,其中將我們創建的defaultListableBeanFactory作為參數傳給了reader的構造函數,這里是為了第四步讀取XML文件做准備。
第四行使用reader解析XML文件,並將讀取的bean定義回調設置到defaultListableBeanFactory當中。其實回調這一步就相當於我們上述的注冊這一步。
(1)Bean 的解析
Bean 的解析 過程非常復雜,功能被分的很細,因為這里需要被擴展的地方很多,必須保證有足夠的靈活性,以應對可能的變化。Bean 的解析主要就是對 Spring 配置文件的解析。這個解析過程主要通過下圖中的類完成:

這個時候defaultListableBeanFactory已經被正確初始化了,我們已經可以使用它的一些方法了,比如上面所使用的獲取bean個數,以及獲得一個bean實例的方法。
1.1
對於ApplicationContext ,代碼為
package com.springframework.beans.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestApplicationContext {
public static void main(String[] args) {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:beans.xml");
System.out.println("numbers: " + applicationContext.getBeanDefinitionCount());
((Person)applicationContext.getBean("person")).work();
}
}
1.2
具體我們在new一個FileSystemXmlApplicationContext對象的時候,spring到底做了哪些事情呢,
先看其構造函數:
調用構造函數:
/**
* Create a new FileSystemXmlApplicationContext, loading the definitions
* from the given XML files and automatically refreshing the context.
* @param configLocations array of file paths
* @throws BeansException if context creation failed
*/public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
實際調用
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
通過分析FileSystemXmlApplicationContext的源代碼可以知道,在創建FileSystemXmlApplicationContext容器時,構造方法做以下兩項重要工作:
1 首先,調用父類容器的構造方法(super(parent)方法)為容器設置好Bean資源加載器。(其繼承體系如下)

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean { //靜態初始化塊,在整個容器創建過程中只執行一次 static { //為了避免應用程序在Weblogic8.1關閉時出現類加載異常加載問題,加載IoC容 //器關閉事件(ContextClosedEvent)類 ContextClosedEvent.class.getName(); } //FileSystemXmlApplicationContext調用父類構造方法調用的就是該方法 public AbstractApplicationContext(ApplicationContext parent) { this.parent = parent; this.resourcePatternResolver = getResourcePatternResolver(); } //獲取一個Spring Source的加載器用於讀入Spring Bean定義資源文件 protected ResourcePatternResolver getResourcePatternResolver() { // AbstractApplicationContext繼承DefaultResourceLoader,也是一個S //Spring資源加載器,其getResource(String location)方法用於載入資源 return new PathMatchingResourcePatternResolver(this); } …… }
AbstractApplicationContext構造方法中調用PathMatchingResourcePatternResolver的構造方法創建Spring資源加載器:
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
//設置Spring的資源加載器
this.resourceLoader = resourceLoader;
}
在設置容器的資源加載器之后,接下來FileSystemXmlApplicationContet執行setConfigLocations方法通過調用其父類AbstractRefreshableConfigApplicationContext的方法進行對Bean定義資源文件的定位,該方法的源碼如下:
//處理單個資源文件路徑為一個字符串的情況
public void setConfigLocation(String location) {
//String CONFIG_LOCATION_DELIMITERS = ",; /t/n";
//即多個資源文件路徑之間用” ,; /t/n”分隔,解析成數組形式
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
//解析Bean定義資源文件的路徑,處理多個資源文件字符串數組
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++) {
// resolvePath為同一個類中將字符串解析為路徑的方法
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
通過這兩個方法的源碼我們可以看出,我們既可以使用一個字符串來配置多個Spring Bean定義資源文件,也可以使用字符串數組,即下面兩種方式都是可以的:
a. ClasspathResource res = new ClasspathResource(“a.xml,b.xml,……”);
多個資源文件路徑之間可以是用” ,; /t/n”等分隔。
b. ClasspathResource res = new ClasspathResource(newString[]{“a.xml”,”b.xml”,……});
至此,Spring IoC容器在初始化時將配置的Bean定義資源文件定位為Spring封裝的Resource。
1.3
refresh方法,便是IOC容器初始化的入口。
Spring IoC容器對Bean定義資源的載入是從refresh()函數開始的,refresh()是一個模板方法,refresh()方法的作用是:在創建IoC容器前,如果已經有容器存在,則需要把已有的容器銷毀和關閉,以保證在refresh之后使用的是新建立起來的IoC容器。refresh的作用類似於對IoC容器的重啟,在新建立好的容器中對容器進行初始化,對Bean定義資源進行載入
FileSystemXmlApplicationContext通過調用其父類AbstractApplicationContext的refresh()函數啟動整個IoC容器對Bean定義的載入過程:
public void refresh() throws BeansException, IllegalStateException {
2 synchronized (this.startupShutdownMonitor) {
3 //調用容器准備刷新的方法,獲取容器的當時時間,同時給容器設置同步標識
4 prepareRefresh();
5 //告訴子類啟動refreshBeanFactory()方法,Bean定義資源文件的載入從
6 //子類的refreshBeanFactory()方法啟動
7 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
8 //為BeanFactory配置容器特性,例如類加載器、事件處理器等
9 prepareBeanFactory(beanFactory);
10 try {
11 //為容器的某些子類指定特殊的BeanPost事件處理器
12 postProcessBeanFactory(beanFactory);
13 //調用所有注冊的BeanFactoryPostProcessor的Bean
14 invokeBeanFactoryPostProcessors(beanFactory);
15 //為BeanFactory注冊BeanPost事件處理器.
16 //BeanPostProcessor是Bean后置處理器,用於監聽容器觸發的事件
17 registerBeanPostProcessors(beanFactory);
18 //初始化信息源,和國際化相關.
19 initMessageSource();
20 //初始化容器事件傳播器.
21 initApplicationEventMulticaster();
22 //調用子類的某些特殊Bean初始化方法
23 onRefresh();
24 //為事件傳播器注冊事件監聽器.
25 registerListeners();
26 //初始化所有剩余的單態Bean.
27 finishBeanFactoryInitialization(beanFactory);
28 //初始化容器的生命周期事件處理器,並發布容器的生命周期事件
29 finishRefresh();
30 }
31 catch (BeansException ex) {
32 //銷毀以創建的單態Bean
33 destroyBeans();
34 //取消refresh操作,重置容器的同步標識.
35 cancelRefresh(ex);
36 throw ex;
37 }
38 }
39 }
refresh()方法主要為IoC容器Bean的生命周期管理提供條件,Spring IoC容器載入Bean定義資源文件從其子類容器的refreshBeanFactory()方法啟動,所以整個refresh()中“ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();”這句以后代碼的都是注冊容器的信息源和生命周期事件,載入過程就是從這句代碼啟動
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//這里使用了委派設計模式,父類定義了抽象的refreshBeanFactory()方法,具體實現調用子類容器的refreshBeanFactory()方法
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
該方法中第一句便調用了另外一個refreshBeanFactory方法,這個方法是AbstractApplicationContext中的抽象方法,具體的實現並沒有在這個抽象類中實現,而是留給了子類,我們追蹤到這個子類當中去看一下。該方法又子類AbstractRefreshableApplicationContext實現,我們來看
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);
}
}
方法加上了final關鍵字,也就是說此方法不可被重寫,可以很清楚的看到,IOC容器的初始化就是在這個方法里發生的,第一步先是判斷有無現有的工廠,有的話便會將其摧毀,否則,就會創建一個默認的bean工廠,也就是前面提到的DefaultListableBeanFactory,注意看loadBeanDefinitions(beanFactory);這里,當我們創建了一個默認的bean工廠以后,便是載入bean的定義。這與我們上一章所使用的原始的創建bean工廠的方式極為相似。
AbstractRefreshableApplicationContext中只定義了抽象的loadBeanDefinitions方法,容器真正調用的是其子類AbstractXmlApplicationContext對該方法的實現,AbstractXmlApplicationContext的主要源碼如下:
1.4
loadBeanDefinitions方法是由AbstractXmlApplicationContext抽象類實現的。
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.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);
}
1.5
第一行首先定義了一個reader,很明顯,這個就是spring為讀取XML配置文件而定制的讀取工具,這里AbstractXmlApplicationContext間接實現了ResourceLoader接口,所以該方法的第二行才得以成立,最后一行便是真正載入bean定義的過程。我們追蹤其根源,可以發現最終的讀取過程正是由reader完成的,代碼如下。
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();
}
}
}
1.6
這個方法中不難發現,try塊中的代碼才是載入bean定義的真正過程,我們一步一步的扒開bean定義的載入,spring將資源返回的輸入流包裝以后傳給了doLoadBeanDefinitions方法,我們進去看看發生了什么。
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
Document doc = this.documentLoader.loadDocument(
inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
可以看到,spring采用documentLoader將資源轉換成了Document接口,這正是我們熟知的SAX對XML解析的重要接口之一,這下不難理解了,可以想象出spring一定是根據XSD文件規定的XML格式,解析了XML文件中的各個節點以及屬性。盡管如此,我們還是跟着registerBeanDefinitions方法進去看看。
XmlBeanDefinitionReader類中的doLoadBeanDefinitions方法是從特定XML文件中實際載入Bean定義資源的方法,該方法在載入Bean定義資源之后將其轉換為Document對象,接下來調用registerBeanDefinitions啟動Spring IoC容器對Bean定義的解析過程,registerBeanDefinitions方法源碼如下:
1 //按照Spring的Bean語義要求將Bean定義資源解析並轉換為容器內部數據結構 2 public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { 3 //得到BeanDefinitionDocumentReader來對xml格式的BeanDefinition解析 4 BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); 5 //獲得容器中注冊的Bean數量 6 int countBefore = getRegistry().getBeanDefinitionCount(); 7 //解析過程入口,這里使用了委派模式,BeanDefinitionDocumentReader只是個接口,//具體的解析實現過程有實現類DefaultBeanDefinitionDocumentReader完成 8 documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); 9 //統計解析的Bean數量 10 return getRegistry().getBeanDefinitionCount() - countBefore; 11 } 12 //創建BeanDefinitionDocumentReader對象,解析Document對象 13 protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() { 14 return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass)); }
1.7解析文件與注冊的具體實現
1解析與注冊的分界點
按照Spring的Bean規則對Document對象解析的過程是在接口BeanDefinitionDocumentReader的實現類DefaultBeanDefinitionDocumentReader中實現的。BeanDefinitionDocumentReader接口通過registerBeanDefinitions方法調用其實現類DefaultBeanDefinitionDocumentReader對Document對象進行解析,解析的代碼如下:
//根據Spring DTD對Bean的定義規則解析Bean定義Document對象
2 public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
3 //獲得XML描述符
4 this.readerContext = readerContext;
5 logger.debug("Loading bean definitions");
6 //獲得Document的根元素
7 Element root = doc.getDocumentElement();
8 //具體的解析過程由BeanDefinitionParserDelegate實現,
9 //BeanDefinitionParserDelegate中定義了Spring Bean定義XML文件的各種元素
10 BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
11 //在解析Bean定義之前,進行自定義的解析,增強解析過程的可擴展性
12 preProcessXml(root);
13 //從Document的根元素開始進行Bean定義的Document對象
14 parseBeanDefinitions(root, delegate);
15 //在解析Bean定義之后,進行自定義的解析,增加解析過程的可擴展性
16 postProcessXml(root);
17 }
18 //創建BeanDefinitionParserDelegate,用於完成真正的解析過程
19 protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) {
20 BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
21 //BeanDefinitionParserDelegate初始化Document根元素
22 delegate.initDefaults(root);
23 return delegate;
24 }
25 //使用Spring的Bean規則從Document的根元素開始進行Bean定義的Document對象
26 protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
27 //Bean定義的Document對象使用了Spring默認的XML命名空間
28 if (delegate.isDefaultNamespace(root)) {
29 //獲取Bean定義的Document對象根元素的所有子節點
30 NodeList nl = root.getChildNodes();
31 for (int i = 0; i < nl.getLength(); i++) {
32 Node node = nl.item(i);
33 //獲得Document節點是XML元素節點
34 if (node instanceof Element) {
35 Element ele = (Element) node;
36 //Bean定義的Document的元素節點使用的是Spring默認的XML命名空間
37 if (delegate.isDefaultNamespace(ele)) {
38 //使用Spring的Bean規則解析元素節點
39 parseDefaultElement(ele, delegate);
40 }
41 else {
42 //沒有使用Spring默認的XML命名空間,則使用用戶自定義的解//析規則解析元素節點
43 delegate.parseCustomElement(ele);
44 }
45 }
46 }
47 }
48 else {
49 //Document的根節點沒有使用Spring默認的命名空間,則使用用戶自定義的
50 //解析規則解析Document根節點
51 delegate.parseCustomElement(root);
52 }
53 }
54 //使用Spring的Bean規則解析Document元素節點
55 private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
56 //如果元素節點是<Import>導入元素,進行導入解析
57 if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
58 importBeanDefinitionResource(ele);
59 }
60 //如果元素節點是<Alias>別名元素,進行別名解析
61 else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
62 processAliasRegistration(ele);
63 }
64 //元素節點既不是導入元素,也不是別名元素,即普通的<Bean>元素,
65 //按照Spring的Bean規則解析元素
66 else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
67 processBeanDefinition(ele, delegate);
68 }
69 }
70 //解析<Import>導入元素,從給定的導入路徑加載Bean定義資源到Spring IoC容器中
71 protected void importBeanDefinitionResource(Element ele) {
72 //獲取給定的導入元素的location屬性
73 String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
74 //如果導入元素的location屬性值為空,則沒有導入任何資源,直接返回
75 if (!StringUtils.hasText(location)) {
76 getReaderContext().error("Resource location must not be empty", ele);
77 return;
78 }
79 //使用系統變量值解析location屬性值
80 location = SystemPropertyUtils.resolvePlaceholders(location);
81 Set<Resource> actualResources = new LinkedHashSet<Resource>(4);
82 //標識給定的導入元素的location是否是絕對路徑
83 boolean absoluteLocation = false;
84 try {
85 absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
86 }
87 catch (URISyntaxException ex) {
88 //給定的導入元素的location不是絕對路徑
89 }
90 //給定的導入元素的location是絕對路徑
91 if (absoluteLocation) {
92 try {
93 //使用資源讀入器加載給定路徑的Bean定義資源
94 int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
95 if (logger.isDebugEnabled()) {
96 logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
97 }
98 }
99 catch (BeanDefinitionStoreException ex) {
100 getReaderContext().error(
101 "Failed to import bean definitions from URL location [" + location + "]", ele, ex);
102 }
103 }
104 else {
105 //給定的導入元素的location是相對路徑
106 try {
107 int importCount;
108 //將給定導入元素的location封裝為相對路徑資源
109 Resource relativeResource = getReaderContext().getResource().createRelative(location);
110 //封裝的相對路徑資源存在
111 if (relativeResource.exists()) {
112 //使用資源讀入器加載Bean定義資源
113 importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
114 actualResources.add(relativeResource);
115 }
116 //封裝的相對路徑資源不存在
117 else {
118 //獲取Spring IoC容器資源讀入器的基本路徑
119 String baseLocation = getReaderContext().getResource().getURL().toString();
120 //根據Spring IoC容器資源讀入器的基本路徑加載給定導入
121 //路徑的資源
122 importCount = getReaderContext().getReader().loadBeanDefinitions(
123 StringUtils.applyRelativePath(baseLocation, location), actualResources);
124 }
125 if (logger.isDebugEnabled()) {
126 logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
127 }
128 }
129 catch (IOException ex) {
130 getReaderContext().error("Failed to resolve current resource location", ele, ex);
131 }
132 catch (BeanDefinitionStoreException ex) {
133 getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
134 ele, ex);
135 }
136 }
137 Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
138 //在解析完<Import>元素之后,發送容器導入其他資源處理完成事件
139 getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
140 }
141 //解析<Alias>別名元素,為Bean向Spring IoC容器注冊別名
142 protected void processAliasRegistration(Element ele) {
143 //獲取<Alias>別名元素中name的屬性值
144 String name = ele.getAttribute(NAME_ATTRIBUTE);
145 //獲取<Alias>別名元素中alias的屬性值
146 String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
147 boolean valid = true;
148 //<alias>別名元素的name屬性值為空
149 if (!StringUtils.hasText(name)) {
150 getReaderContext().error("Name must not be empty", ele);
151 valid = false;
152 }
153 //<alias>別名元素的alias屬性值為空
154 if (!StringUtils.hasText(alias)) {
155 getReaderContext().error("Alias must not be empty", ele);
156 valid = false;
157 }
158 if (valid) {
159 try {
160 //向容器的資源讀入器注冊別名
161 getReaderContext().getRegistry().registerAlias(name, alias);
162 }
163 catch (Exception ex) {
164 getReaderContext().error("Failed to register alias '" + alias +
165 "' for bean with name '" + name + "'", ele, ex);
166 }
167 //在解析完<Alias>元素之后,發送容器別名處理完成事件
168 getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
169 }
170 }
171 //解析Bean定義資源Document對象的普通元素
172 protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
173 // BeanDefinitionHolder是對BeanDefinition的封裝,即Bean定義的封裝類
174 //對Document對象中<Bean>元素的解析由BeanDefinitionParserDelegate實現
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
175 if (bdHolder != null) {
176 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
177 try {
178 //向Spring IoC容器注冊解析得到的Bean定義,這是Bean定義向IoC容器注冊的入口
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
179 }
180 catch (BeanDefinitionStoreException ex) {
181 getReaderContext().error("Failed to register bean definition with name '" +
182 bdHolder.getBeanName() + "'", ele, ex);
183 }
184 //在完成向Spring IoC容器注冊解析得到的Bean定義之后,發送注冊事件
185 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
186 }
187 }
2 具體解析過程
對Bean定義資源文件中使用最多的<Bean>元素交由BeanDefinitionParserDelegate中parseBeanDefinitionElement來解析,其解析實現的源碼如下:
//解析<Bean>元素的入口
2 public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
3 return parseBeanDefinitionElement(ele, null);
4 }
5 //解析Bean定義資源文件中的<Bean>元素,這個方法中主要處理<Bean>元素的id,name
6 //和別名屬性
7 public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
8 //獲取<Bean>元素中的id屬性值
9 String id = ele.getAttribute(ID_ATTRIBUTE);
10 //獲取<Bean>元素中的name屬性值
11 String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
12 ////獲取<Bean>元素中的alias屬性值
13 List<String> aliases = new ArrayList<String>();
14 //將<Bean>元素中的所有name屬性值存放到別名中
15 if (StringUtils.hasLength(nameAttr)) {
16 String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS);
17 aliases.addAll(Arrays.asList(nameArr));
18 }
19 String beanName = id;
20 //如果<Bean>元素中沒有配置id屬性時,將別名中的第一個值賦值給beanName
21 if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
22 beanName = aliases.remove(0);
23 if (logger.isDebugEnabled()) {
24 logger.debug("No XML 'id' specified - using '" + beanName +
25 "' as bean name and " + aliases + " as aliases");
26 }
27 }
28 //檢查<Bean>元素所配置的id或者name的唯一性,containingBean標識<Bean>
29 //元素中是否包含子<Bean>元素
30 if (containingBean == null) {
31 //檢查<Bean>元素所配置的id、name或者別名是否重復
32 checkNameUniqueness(beanName, aliases, ele);
33 }
34 //詳細對<Bean>元素中配置的Bean定義進行解析的地方
35 AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
36 if (beanDefinition != null) {
37 if (!StringUtils.hasText(beanName)) {
38 try {
39 if (containingBean != null) {
40 //如果<Bean>元素中沒有配置id、別名或者name,且沒有包含子//<Bean>元素,為解析的Bean生成一個唯一beanName並注冊
41 beanName = BeanDefinitionReaderUtils.generateBeanName(
42 beanDefinition, this.readerContext.getRegistry(), true);
43 }
44 else {
45 //如果<Bean>元素中沒有配置id、別名或者name,且包含了子//<Bean>元素,為解析的Bean使用別名向IoC容器注冊
46 beanName = this.readerContext.generateBeanName(beanDefinition);
47 //為解析的Bean使用別名注冊時,為了向后兼容 //Spring1.2/2.0,給別名添加類名后綴
48 String beanClassName = beanDefinition.getBeanClassName();
49 if (beanClassName != null &&
50 beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
51 !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
52 aliases.add(beanClassName);
53 }
54 }
55 if (logger.isDebugEnabled()) {
56 logger.debug("Neither XML 'id' nor 'name' specified - " +
57 "using generated bean name [" + beanName + "]");
58 }
59 }
60 catch (Exception ex) {
61 error(ex.getMessage(), ele);
62 return null;
63 }
64 }
65 String[] aliasesArray = StringUtils.toStringArray(aliases);
66 return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
67 }
68 //當解析出錯時,返回null
69 return null;
70 }
71 //詳細對<Bean>元素中配置的Bean定義其他屬性進行解析,由於上面的方法中已經對//Bean的id、name和別名等屬性進行了處理,該方法中主要處理除這三個以外的其他屬性數據
72 public AbstractBeanDefinition parseBeanDefinitionElement(
73 Element ele, String beanName, BeanDefinition containingBean) {
74 //記錄解析的<Bean>
75 this.parseState.push(new BeanEntry(beanName));
76 //這里只讀取<Bean>元素中配置的class名字,然后載入到BeanDefinition中去
77 //只是記錄配置的class名字,不做實例化,對象的實例化在依賴注入時完成
78 String className = null;
79 if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
80 className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
81 }
82 try {
83 String parent = null;
84 //如果<Bean>元素中配置了parent屬性,則獲取parent屬性的值
85 if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
86 parent = ele.getAttribute(PARENT_ATTRIBUTE);
87 }
88 //根據<Bean>元素配置的class名稱和parent屬性值創建BeanDefinition
89 //為載入Bean定義信息做准備
90 AbstractBeanDefinition bd = createBeanDefinition(className, parent);
91 //對當前的<Bean>元素中配置的一些屬性進行解析和設置,如配置的單態(singleton)屬性等
92 parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
93 //為<Bean>元素解析的Bean設置description信息 bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
94 //對<Bean>元素的meta(元信息)屬性解析
95 parseMetaElements(ele, bd);
96 //對<Bean>元素的lookup-method屬性解析
97 parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
98 //對<Bean>元素的replaced-method屬性解析
99 parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
100 //解析<Bean>元素的構造方法設置
101 parseConstructorArgElements(ele, bd);
102 //解析<Bean>元素的<property>設置
103 parsePropertyElements(ele, bd);
104 //解析<Bean>元素的qualifier屬性
105 parseQualifierElements(ele, bd);
106 //為當前解析的Bean設置所需的資源和依賴對象
107 bd.setResource(this.readerContext.getResource());
108 bd.setSource(extractSource(ele));
109 return bd;
110 }
111 catch (ClassNotFoundException ex) {
112 error("Bean class [" + className + "] not found", ele, ex);
113 }
114 catch (NoClassDefFoundError err) {
115 error("Class that bean class [" + className + "] depends on not found", ele, err);
116 }
117 catch (Throwable ex) {
118 error("Unexpected failure during bean definition parsing", ele, ex);
119 }
120 finally {
121 this.parseState.pop();
122 }
123 //解析<Bean>元素出錯時,返回null
124 return null;
125 }
注意:在解析<Bean>元素過程中沒有創建和實例化Bean對象,只是創建了Bean對象的定義類BeanDefinition,將<Bean>元素中的配置信息設置到BeanDefinition中作為記錄,當依賴注入時才使用這些記錄信息創建和實例化具體的Bean對象。
上面方法中一些對一些配置如元信息(meta)、qualifier等的解析,我們在Spring中配置時使用的也不多,我們在使用Spring的<Bean>元素時,配置最多的是<property>屬性,因此我們下面繼續分析源碼,了解Bean的屬性在解析時是如何設置的。
復制代碼
1 //解析<Bean>元素中的<property>子元素
2 public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
3 //獲取<Bean>元素中所有的子元素
4 NodeList nl = beanEle.getChildNodes();
5 for (int i = 0; i < nl.getLength(); i++) {
6 Node node = nl.item(i);
7 //如果子元素是<property>子元素,則調用解析<property>子元素方法解析
8 if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
9 parsePropertyElement((Element) node, bd);
10 }
11 }
12 }
13 //解析<property>元素
14 public void parsePropertyElement(Element ele, BeanDefinition bd) {
15 //獲取<property>元素的名字
16 String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
17 if (!StringUtils.hasLength(propertyName)) {
18 error("Tag 'property' must have a 'name' attribute", ele);
19 return;
20 }
21 this.parseState.push(new PropertyEntry(propertyName));
22 try {
23 //如果一個Bean中已經有同名的property存在,則不進行解析,直接返回。
24 //即如果在同一個Bean中配置同名的property,則只有第一個起作用
25 if (bd.getPropertyValues().contains(propertyName)) {
26 error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
27 return;
28 }
29 //解析獲取property的值
30 Object val = parsePropertyValue(ele, bd, propertyName);
31 //根據property的名字和值創建property實例
32 PropertyValue pv = new PropertyValue(propertyName, val);
33 //解析<property>元素中的屬性
34 parseMetaElements(ele, pv);
35 pv.setSource(extractSource(ele));
36 bd.getPropertyValues().addPropertyValue(pv);
37 }
38 finally {
39 this.parseState.pop();
40 }
41 }
42 //解析獲取property值
43 public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
44 String elementName = (propertyName != null) ?
45 "<property> element for property '" + propertyName + "'" :
46 "<constructor-arg> element";
47 //獲取<property>的所有子元素,只能是其中一種類型:ref,value,list等
48 NodeList nl = ele.getChildNodes();
49 Element subElement = null;
50 for (int i = 0; i < nl.getLength(); i++) {
51 Node node = nl.item(i);
52 //子元素不是description和meta屬性
53 if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
54 !nodeNameEquals(node, META_ELEMENT)) {
55 if (subElement != null) {
56 error(elementName + " must not contain more than one sub-element", ele);
57 }
58 else {//當前<property>元素包含有子元素
59 subElement = (Element) node;
60 }
61 }
62 }
63 //判斷property的屬性值是ref還是value,不允許既是ref又是value
64 boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
65 boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
66 if ((hasRefAttribute && hasValueAttribute) ||
67 ((hasRefAttribute || hasValueAttribute) && subElement != null)) {
68 error(elementName +
69 " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
70 }
71 //如果屬性是ref,創建一個ref的數據對象RuntimeBeanReference,這個對象
72 //封裝了ref信息
73 if (hasRefAttribute) {
74 String refName = ele.getAttribute(REF_ATTRIBUTE);
75 if (!StringUtils.hasText(refName)) {
76 error(elementName + " contains empty 'ref' attribute", ele);
77 }
78 //一個指向運行時所依賴對象的引用
79 RuntimeBeanReference ref = new RuntimeBeanReference(refName);
80 //設置這個ref的數據對象是被當前的property對象所引用
81 ref.setSource(extractSource(ele));
82 return ref;
83 }
84 //如果屬性是value,創建一個value的數據對象TypedStringValue,這個對象
85 //封裝了value信息
86 else if (hasValueAttribute) {
87 //一個持有String類型值的對象
88 TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
89 //設置這個value數據對象是被當前的property對象所引用
90 valueHolder.setSource(extractSource(ele));
91 return valueHolder;
92 }
93 //如果當前<property>元素還有子元素
94 else if (subElement != null) {
95 //解析<property>的子元素
96 return parsePropertySubElement(subElement, bd);
97 }
98 else {
99 //propery屬性中既不是ref,也不是value屬性,解析出錯返回null error(elementName + " must specify a ref or value", ele);
100 return null;
101 }
}
通過上述源碼分析,我們明白了在Spring配置文件中,對<property>元素中配置的Array、List、Set、Map、Prop等各種集合子元素的都通過上述方法解析,生成對應的數據對象,比如ManagedList、ManagedArray、ManagedSet等,這些Managed類是Spring對象BeanDefiniton的數據封裝,對集合數據類型的具體解析有各自的解析方法實現,解析方法的命名非常規范,一目了然,我們對<list>集合元素的解析方法進行源碼分析,了解其實現過程。在BeanDefinitionParserDelegate類中的parseListElement方法就是具體實現解析<property>元素中的<list>集合子元素,源碼如下:
//解析<list>集合子元素
2 public List parseListElement(Element collectionEle, BeanDefinition bd) {
3 //獲取<list>元素中的value-type屬性,即獲取集合元素的數據類型
4 String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
5 //獲取<list>集合元素中的所有子節點
6 NodeList nl = collectionEle.getChildNodes();
7 //Spring中將List封裝為ManagedList
8 ManagedList<Object> target = new ManagedList<Object>(nl.getLength());
9 target.setSource(extractSource(collectionEle));
10 //設置集合目標數據類型
11 target.setElementTypeName(defaultElementType);
12 target.setMergeEnabled(parseMergeAttribute(collectionEle));
13 //具體的<list>元素解析
14 parseCollectionElements(nl, target, bd, defaultElementType);
15 return target;
16 }
17 //具體解析<list>集合元素,<array>、<list>和<set>都使用該方法解析
18 protected void parseCollectionElements(
19 NodeList elementNodes, Collection<Object> target, BeanDefinition bd, String defaultElementType) {
20 //遍歷集合所有節點
21 for (int i = 0; i < elementNodes.getLength(); i++) {
22 Node node = elementNodes.item(i);
23 //節點不是description節點
24 if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
25 //將解析的元素加入集合中,遞歸調用下一個子元素
26 target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
27 }
28 }
}
經過對Spring Bean定義資源文件轉換的Document對象中的元素層層解析,Spring IoC現在已經將XML形式定義的Bean定義資源文件轉換為Spring IoC所識別的數據結構——BeanDefinition,它是Bean定義資源文件中配置的POJO對象在Spring IoC容器中的映射,我們可以通過AbstractBeanDefinition為入口,榮IoC容器進行索引、查詢和操作。
通過Spring IoC容器對Bean定義資源的解析后,IoC容器大致完成了管理Bean對象的准備工作,即初始化過程,但是最為重要的依賴注入還沒有發生,現在在IoC容器中BeanDefinition存儲的只是一些靜態信息,接下來需要向容器注冊Bean定義信息才能全部完成IoC容器的初始化過程
3接下來是注冊過程
DefaultBeanDefinitionDocumentReader對Bean定義轉換的Document對象解析的流程中,在其parseDefaultElement方法中完成對Document對象的解析后得到封裝BeanDefinition的BeanDefinitionHold對象,然后調用BeanDefinitionReaderUtils的registerBeanDefinition方法向IoC容器注冊解析的Bean,BeanDefinitionReaderUtils的注冊的源碼如下:
//將解析的BeanDefinitionHold注冊到容器中 public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { //獲取解析的BeanDefinition的名稱 String beanName = definitionHolder.getBeanName(); //向IoC容器注冊BeanDefinition registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); //如果解析的BeanDefinition有別名,向容器為其注冊別名 String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String aliase : aliases) { registry.registerAlias(beanName, aliase); } } }
registerBeanDefinition方法在DefaultListableBeanFactory,它中使用一個HashMap的集合對象存放IoC容器中注冊解析的BeanDefinition,向IoC容器注冊的主要代碼為:
//存儲注冊的俄BeanDefinition
2 private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
3 //向IoC容器注冊解析的BeanDefiniton
4 public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
5 throws BeanDefinitionStoreException {
6 Assert.hasText(beanName, "Bean name must not be empty");
7 Assert.notNull(beanDefinition, "BeanDefinition must not be null");
8 //校驗解析的BeanDefiniton
9 if (beanDefinition instanceof AbstractBeanDefinition) {
10 try {
11 ((AbstractBeanDefinition) beanDefinition).validate();
12 }
13 catch (BeanDefinitionValidationException ex) {
14 throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
15 "Validation of bean definition failed", ex);
16 }
17 }
18 //注冊的過程中需要線程同步,以保證數據的一致性
19 synchronized (this.beanDefinitionMap) {
20 Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
21 //檢查是否有同名的BeanDefinition已經在IoC容器中注冊,如果已經注冊,
22 //並且不允許覆蓋已注冊的Bean,則拋出注冊失敗異常
23 if (oldBeanDefinition != null) {
24 if (!this.allowBeanDefinitionOverriding) {
25 throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
26 "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
27 "': There is already [" + oldBeanDefinition + "] bound.");
28 }
29 else {//如果允許覆蓋,則同名的Bean,后注冊的覆蓋先注冊的
30 if (this.logger.isInfoEnabled()) {
31 this.logger.info("Overriding bean definition for bean '" + beanName +
32 "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
33 }
34 }
35 }
36 //IoC容器中沒有已經注冊同名的Bean,按正常注冊流程注冊
37 else {
38 this.beanDefinitionNames.add(beanName);
39 this.frozenBeanDefinitionNames = null;
40 }
41 this.beanDefinitionMap.put(beanName, beanDefinition);
42 //重置所有已經注冊過的BeanDefinition的緩存
43 resetBeanDefinition(beanName);
44 }
}
復制代碼
至此,Bean定義資源文件中配置的Bean被解析過后,已經注冊到IoC容器中,被容器管理起來,真正完成了IoC容器初始化所做的全部工作。現 在IoC容器中已經建立了整個Bean的配置信息,這些BeanDefinition信息已經可以使用,並且可以被檢索,IoC容器的作用就是對這些注冊的Bean定義信息進行處理和維護。這些的注冊的Bean定義信息是IoC容器控制反轉的基礎,正是有了這些注冊的數據,容器才可以進行依賴注入。
(4)依賴注入
1
當Spring IoC容器完成了Bean定義資源的定位、載入和解析注冊以后,IoC容器中已經管理類Bean定義的相關數據,但是此時IoC容器還沒有對所管理的Bean進行依賴注入,依賴注入在以下兩種情況發生:
(1).用戶第一次通過getBean方法向IoC容索要Bean時,IoC容器觸發依賴注入。
(2).當用戶在Bean定義資源中為<Bean>元素配置了lazy-init屬性,即讓容器在解析注冊Bean定義時進行預實例化,觸發依賴注入。
BeanFactory接口定義了Spring IoC容器的基本功能規范,是Spring IoC容器所應遵守的最底層和最基本的編程規范。BeanFactory接口中定義了幾個getBean方法,就是用戶向IoC容器索取管理的Bean的方法,我們通過分析其子類的具體實現,理解Spring IoC容器在用戶索取Bean時如何完成依賴注入。
在BeanFactory中我們看到getBean(String…)函數,它的具體實現在AbstractBeanFactory中。

具體代碼為
package org.springframework.beans.factory.support;
import org.springframework.beans.factory.BeanFactory;
1 //獲取IoC容器中指定名稱的Bean 2 public Object getBean(String name) throws BeansException { 3 //doGetBean才是真正向IoC容器獲取被管理Bean的過程 4 return doGetBean(name, null, null, false); 5 } 6 //獲取IoC容器中指定名稱和類型的Bean 7 public <T> T getBean(String name, Class<T> requiredType) throws BeansException { 8 //doGetBean才是真正向IoC容器獲取被管理Bean的過程 9 return doGetBean(name, requiredType, null, false); 10 } 11 //獲取IoC容器中指定名稱和參數的Bean 12 public Object getBean(String name, Object... args) throws BeansException { 13 //doGetBean才是真正向IoC容器獲取被管理Bean的過程 14 return doGetBean(name, null, args, false); 15 } 16 //獲取IoC容器中指定名稱、類型和參數的Bean 17 public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { 18 //doGetBean才是真正向IoC容器獲取被管理Bean的過程 19 return doGetBean(name, requiredType, args, false); 20 } 21 //真正實現向IoC容器獲取Bean的功能,也是觸發依賴注入功能的地方 22 @SuppressWarnings("unchecked") 23 protected <T> T doGetBean( 24 final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) 25 throws BeansException { 26 //根據指定的名稱獲取被管理Bean的名稱,剝離指定名稱中對容器的相關依賴 27 //如果指定的是別名,將別名轉換為規范的Bean名稱 28 final String beanName = transformedBeanName(name); 29 Object bean; 30 //先從緩存中取是否已經有被創建過的單態類型的Bean,對於單態模式的Bean整 31 //個IoC容器中只創建一次,不需要重復創建 32 Object sharedInstance = getSingleton(beanName); 33 //IoC容器創建單態模式Bean實例對象 34 if (sharedInstance != null && args == null) { 35 if (logger.isDebugEnabled()) { 36 //如果指定名稱的Bean在容器中已有單態模式的Bean被創建,直接返回 37 //已經創建的Bean 38 if (isSingletonCurrentlyInCreation(beanName)) { 39 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 40 "' that is not fully initialized yet - a consequence of a circular reference"); 41 } 42 else { 43 logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); 44 } 45 } 46 //獲取給定Bean的實例對象,主要是完成FactoryBean的相關處理 47 //注意:BeanFactory是管理容器中Bean的工廠,而FactoryBean是 48 //創建創建對象的工廠Bean,兩者之間有區別 49 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 50 } 51 else {//緩存沒有正在創建的單態模式Bean 52 //緩存中已經有已經創建的原型模式Bean,但是由於循環引用的問題導致實 53 //例化對象失敗 54 if (isPrototypeCurrentlyInCreation(beanName)) { 55 throw new BeanCurrentlyInCreationException(beanName); 56 } 57 //對IoC容器中是否存在指定名稱的BeanDefinition進行檢查,首先檢查是否 58 //能在當前的BeanFactory中獲取的所需要的Bean,如果不能則委托當前容器 59 //的父級容器去查找,如果還是找不到則沿着容器的繼承體系向父級容器查找 60 BeanFactory parentBeanFactory = getParentBeanFactory(); 61 //當前容器的父級容器存在,且當前容器中不存在指定名稱的Bean 62 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 63 //解析指定Bean名稱的原始名稱 64 String nameToLookup = originalBeanName(name); 65 if (args != null) { 66 //委派父級容器根據指定名稱和顯式的參數查找 67 return (T) parentBeanFactory.getBean(nameToLookup, args); 68 } 69 else { 70 //委派父級容器根據指定名稱和類型查找 71 return parentBeanFactory.getBean(nameToLookup, requiredType); 72 } 73 } 74 //創建的Bean是否需要進行類型驗證,一般不需要 75 if (!typeCheckOnly) { 76 //向容器標記指定的Bean已經被創建 77 markBeanAsCreated(beanName); 78 } 79 //根據指定Bean名稱獲取其父級的Bean定義,主要解決Bean繼承時子類 80 //合並父類公共屬性問題 81 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 82 checkMergedBeanDefinition(mbd, beanName, args); 83 //獲取當前Bean所有依賴Bean的名稱 84 String[] dependsOn = mbd.getDependsOn(); 85 //如果當前Bean有依賴Bean 86 if (dependsOn != null) { 87 for (String dependsOnBean : dependsOn) { 88 //遞歸調用getBean方法,獲取當前Bean的依賴Bean 89 getBean(dependsOnBean); 90 //把被依賴Bean注冊給當前依賴的Bean 91 registerDependentBean(dependsOnBean, beanName); 92 } 93 } 94 //創建單態模式Bean的實例對象 95 if (mbd.isSingleton()) { 96 //這里使用了一個匿名內部類,創建Bean實例對象,並且注冊給所依賴的對象 97 sharedInstance = getSingleton(beanName, new ObjectFactory() { 98 public Object getObject() throws BeansException { 99 try { 100 //創建一個指定Bean實例對象,如果有父級繼承,則合並子//類和父類的定義 101 return createBean(beanName, mbd, args); 102 } 103 catch (BeansException ex) { 104 //顯式地從容器單態模式Bean緩存中清除實例對象 105 destroySingleton(beanName); 106 throw ex; 107 } 108 } 109 }); 110 //獲取給定Bean的實例對象 111 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 112 } 113 //IoC容器創建原型模式Bean實例對象 114 else if (mbd.isPrototype()) { 115 //原型模式(Prototype)是每次都會創建一個新的對象 116 Object prototypeInstance = null; 117 try { 118 //回調beforePrototypeCreation方法,默認的功能是注冊當前創//建的原型對象 119 beforePrototypeCreation(beanName); 120 //創建指定Bean對象實例 121 prototypeInstance = createBean(beanName, mbd, args); 122 } 123 finally { 124 //回調afterPrototypeCreation方法,默認的功能告訴IoC容器指//定Bean的原型對象不再創建了 125 afterPrototypeCreation(beanName); 126 } 127 //獲取給定Bean的實例對象 128 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 129 } 130 //要創建的Bean既不是單態模式,也不是原型模式,則根據Bean定義資源中 131 //配置的生命周期范圍,選擇實例化Bean的合適方法,這種在Web應用程序中 132 //比較常用,如:request、session、application等生命周期 133 else { 134 String scopeName = mbd.getScope(); 135 final Scope scope = this.scopes.get(scopeName); 136 //Bean定義資源中沒有配置生命周期范圍,則Bean定義不合法 137 if (scope == null) { 138 throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); 139 } 140 try { 141 //這里又使用了一個匿名內部類,獲取一個指定生命周期范圍的實例 142 Object scopedInstance = scope.get(beanName, new ObjectFactory() { 143 public Object getObject() throws BeansException { 144 beforePrototypeCreation(beanName); 145 try { 146 return createBean(beanName, mbd, args); 147 } 148 finally { 149 afterPrototypeCreation(beanName); 150 } 151 } 152 }); 153 //獲取給定Bean的實例對象 154 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 155 } 156 catch (IllegalStateException ex) { 157 throw new BeanCreationException(beanName, 158 "Scope '" + scopeName + "' is not active for the current thread; " + 159 "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", 160 ex); 161 } 162 } 163 } 164 //對創建的Bean實例對象進行類型檢查 165 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { 166 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 167 } 168 return (T) bean; 169 }
通過上面對向IoC容器獲取Bean方法的分析,我們可以看到在Spring中,如果Bean定義的單態模式(Singleton),則容器在創建之前先從緩存中查找,以確保整個容器中只存在一個實例對象。如果Bean定義的是原型模式(Prototype),則容器每次都會創建一個新的實例對象。除此之外,Bean定義還可以擴展為指定其生命周期范圍。
2
上面的源碼只是定義了根據Bean定義的模式,采取的不同創建Bean實例對象的策略,具體的Bean實例對象的創建過程由實現了ObejctFactory接口的匿名內部類的createBean方法完成,ObejctFactory使用委派模式,具體的Bean實例創建過程交由其實現類AbstractAutowireCapableBeanFactory完成,我們繼續分析AbstractAutowireCapableBeanFactory的createBean方法的源碼,理解其創建Bean實例的具體實現過程。
AbstractAutowireCapableBeanFactory類實現了ObejctFactory接口,創建容器指定的Bean實例對象,同時還對創建的Bean實例對象進行初始化處理。其創建Bean實例對象的方法源碼如下:
1 //創建Bean實例對象
2 protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
3 throws BeanCreationException {
4 if (logger.isDebugEnabled()) {
5 logger.debug("Creating instance of bean '" + beanName + "'");
6 }
7 //判斷需要創建的Bean是否可以實例化,即是否可以通過當前的類加載器加載
8 resolveBeanClass(mbd, beanName);
9 //校驗和准備Bean中的方法覆蓋
10 try {
11 mbd.prepareMethodOverrides();
12 }
13 catch (BeanDefinitionValidationException ex) {
14 throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
15 beanName, "Validation of method overrides failed", ex);
16 }
17 try {
18 //如果Bean配置了初始化前和初始化后的處理器,則試圖返回一個需要創建//Bean的代理對象
19 Object bean = resolveBeforeInstantiation(beanName, mbd);
20 if (bean != null) {
21 return bean;
22 }
23 }
24 catch (Throwable ex) {
25 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
26 "BeanPostProcessor before instantiation of bean failed", ex);
27 }
28 //創建Bean的入口
29 Object beanInstance = doCreateBean(beanName, mbd, args);
30 if (logger.isDebugEnabled()) {
31 logger.debug("Finished creating instance of bean '" + beanName + "'");
32 }
33 return beanInstance;
34 }
35 //真正創建Bean的方法
36 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
37 //封裝被創建的Bean對象
38 BeanWrapper instanceWrapper = null;
39 if (mbd.isSingleton()){//單態模式的Bean,先從容器中緩存中獲取同名Bean
40 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
41 }
42 if (instanceWrapper == null) {
43 //創建實例對象
44 instanceWrapper = createBeanInstance(beanName, mbd, args);
45 }
46 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
47 //獲取實例化對象的類型
48 Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
49 //調用PostProcessor后置處理器
50 synchronized (mbd.postProcessingLock) {
51 if (!mbd.postProcessed) {
52 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
53 mbd.postProcessed = true;
54 }
55 }
56 // Eagerly cache singletons to be able to resolve circular references
57 //向容器中緩存單態模式的Bean對象,以防循環引用
58 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
59 isSingletonCurrentlyInCreation(beanName));
60 if (earlySingletonExposure) {
61 if (logger.isDebugEnabled()) {
62 logger.debug("Eagerly caching bean '" + beanName +
63 "' to allow for resolving potential circular references");
64 }
65 //這里是一個匿名內部類,為了防止循環引用,盡早持有對象的引用
66 addSingletonFactory(beanName, new ObjectFactory() {
67 public Object getObject() throws BeansException {
68 return getEarlyBeanReference(beanName, mbd, bean);
69 }
70 });
71 }
72 //Bean對象的初始化,依賴注入在此觸發
73 //這個exposedObject在初始化完成之后返回作為依賴注入完成后的Bean
74 Object exposedObject = bean;
75 try {
76 //將Bean實例對象封裝,並且Bean定義中配置的屬性值賦值給實例對象
77 populateBean(beanName, mbd, instanceWrapper);
78 if (exposedObject != null) {
79 //初始化Bean對象
80 exposedObject = initializeBean(beanName, exposedObject, mbd);
81 }
82 }
83 catch (Throwable ex) {
84 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
85 throw (BeanCreationException) ex;
86 }
87 else {
88 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
89 }
90 }
91 if (earlySingletonExposure) {
92 //獲取指定名稱的已注冊的單態模式Bean對象
93 Object earlySingletonReference = getSingleton(beanName, false);
94 if (earlySingletonReference != null) {
95 //根據名稱獲取的以注冊的Bean和正在實例化的Bean是同一個
96 if (exposedObject == bean) {
97 //當前實例化的Bean初始化完成
98 exposedObject = earlySingletonReference;
99 }
100 //當前Bean依賴其他Bean,並且當發生循環引用時不允許新創建實例對象
101 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
102 String[] dependentBeans = getDependentBeans(beanName);
103 Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
104 //獲取當前Bean所依賴的其他Bean
105 for (String dependentBean : dependentBeans) {
106 //對依賴Bean進行類型檢查
107 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
108 actualDependentBeans.add(dependentBean);
109 }
110 }
111 if (!actualDependentBeans.isEmpty()) {
112 throw new BeanCurrentlyInCreationException(beanName,
113 "Bean with name '" + beanName + "' has been injected into other beans [" +
114 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
115 "] in its raw version as part of a circular reference, but has eventually been " +
116 "wrapped. This means that said other beans do not use the final version of the " +
117 "bean. This is often the result of over-eager type matching - consider using " +
118 "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
119 }
120 }
121 }
122 }
123 //注冊完成依賴注入的Bean
124 try {
125 registerDisposableBeanIfNecessary(beanName, bean, mbd);
126 }
127 catch (BeanDefinitionValidationException ex) {
128 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
129 }
130 return exposedObject;
}
下面繼續分析這兩個方法的代碼實現。
3
createBeanInstance方法創建Bean的java實例對象:
在createBeanInstance方法中,根據指定的初始化策略,使用靜態工廠、工廠方法或者容器的自動裝配特性生成java實例對象,創建對象的源碼如下:
通過對方法源碼的分析,我們看到具體的依賴注入實現在以下兩個方法中:
(1).createBeanInstance:生成Bean所包含的java對象實例。
(2).populateBean :對Bean屬性的依賴注入進行處理。
1 //創建Bean的實例對象
2 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
3 //檢查確認Bean是可實例化的
4 Class beanClass = resolveBeanClass(mbd, beanName);
5 //使用工廠方法對Bean進行實例化
6 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
7 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
8 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
9 }
10 if (mbd.getFactoryMethodName() != null) {
11 //調用工廠方法實例化
12 return instantiateUsingFactoryMethod(beanName, mbd, args);
13 }
14 //使用容器的自動裝配方法進行實例化
15 boolean resolved = false;
16 boolean autowireNecessary = false;
17 if (args == null) {
18 synchronized (mbd.constructorArgumentLock) {
19 if (mbd.resolvedConstructorOrFactoryMethod != null) {
20 resolved = true;
21 autowireNecessary = mbd.constructorArgumentsResolved;
22 }
23 }
24 }
25 if (resolved) {
26 if (autowireNecessary) {
27 //配置了自動裝配屬性,使用容器的自動裝配實例化
28 //容器的自動裝配是根據參數類型匹配Bean的構造方法
29 return autowireConstructor(beanName, mbd, null, null);
30 }
31 else {
32 //使用默認的無參構造方法實例化
33 return instantiateBean(beanName, mbd);
34 }
35 }
36 //使用Bean的構造方法進行實例化
37 Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
38 if (ctors != null ||
39 mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
40 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
41 //使用容器的自動裝配特性,調用匹配的構造方法實例化
42 return autowireConstructor(beanName, mbd, ctors, args);
43 }
44 //使用默認的無參構造方法實例化
45 return instantiateBean(beanName, mbd);
46 }
47 //使用默認的無參構造方法實例化Bean對象
48 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
49 try {
50 Object beanInstance;
51 final BeanFactory parent = this;
52 //獲取系統的安全管理接口,JDK標准的安全管理API
53 if (System.getSecurityManager() != null) {
54 //這里是一個匿名內置類,根據實例化策略創建實例對象
55 beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
56 public Object run() {
57 return getInstantiationStrategy().instantiate(mbd, beanName, parent);
58 }
59 }, getAccessControlContext());
60 }
61 else {
62 //將實例化的對象封裝起來
63 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
64 }
65 BeanWrapper bw = new BeanWrapperImpl(beanInstance);
66 initBeanWrapper(bw);
67 return bw;
68 }
69 catch (Throwable ex) {
70 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
71 }
72 }
我們最常使用的默認無參構造方法就需要使用相應的初始化策略(JDK的反射機制或者CGLIB)來進行初始化了,在方法getInstantiationStrategy().instantiate中就具體實現類使用初始策略實例化對象。
方法getInstantiationStrategy().instantiate調用了SimpleInstantiationStrategy類中的實例化Bean的方法,其源碼如下:
1 //使用初始化策略實例化Bean對象
2 public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
3 //如果Bean定義中沒有方法覆蓋,則就不需要CGLIB父類類的方法
4 if (beanDefinition.getMethodOverrides().isEmpty()) {
5 Constructor<?> constructorToUse;
6 synchronized (beanDefinition.constructorArgumentLock) {
7 //獲取對象的構造方法或工廠方法
8 constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
9 //如果沒有構造方法且沒有工廠方法
10 if (constructorToUse == null) {
11 //使用JDK的反射機制,判斷要實例化的Bean是否是接口
12 final Class clazz = beanDefinition.getBeanClass();
13 if (clazz.isInterface()) {
14 throw new BeanInstantiationException(clazz, "Specified class is an interface");
15 }
16 try {
17 if (System.getSecurityManager() != null) {
18 //這里是一個匿名內置類,使用反射機制獲取Bean的構造方法
19 constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() {
20 public Constructor run() throws Exception {
21 return clazz.getDeclaredConstructor((Class[]) null);
22 }
23 });
24 }
25 else {
26 constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
27 }
28 beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
29 }
30 catch (Exception ex) {
31 throw new BeanInstantiationException(clazz, "No default constructor found", ex);
32 }
33 }
34 }
35 //使用BeanUtils實例化,通過反射機制調用”構造方法.newInstance(arg)”來進行實例化
36 return BeanUtils.instantiateClass(constructorToUse);
37 }
38 else {
39 //使用CGLIB來實例化對象
40 return instantiateWithMethodInjection(beanDefinition, beanName, owner);
41 }
}
通過上面的代碼分析,我們看到了如果Bean有方法被覆蓋了,則使用JDK的反射機制進行實例化,否則,使用CGLIB進行實例化。
instantiateWithMethodInjection方法調用SimpleInstantiationStrategy的子類CglibSubclassingInstantiationStrategy使用CGLIB來進行初始化,其源碼如下:
1 //使用CGLIB進行Bean對象實例化
2 public Object instantiate(Constructor ctor, Object[] args) {
3 //CGLIB中的類
4 Enhancer enhancer = new Enhancer();
5 //將Bean本身作為其基類
6 enhancer.setSuperclass(this.beanDefinition.getBeanClass());
7 enhancer.setCallbackFilter(new CallbackFilterImpl());
8 enhancer.setCallbacks(new Callback[] {
9 NoOp.INSTANCE,
10 new LookupOverrideMethodInterceptor(),
11 new ReplaceOverrideMethodInterceptor()
12 });
13 //使用CGLIB的create方法生成實例對象
14 return (ctor == null) ?
15 enhancer.create() :
16 enhancer.create(ctor.getParameterTypes(), args);
17 }
復制代碼
CGLIB是一個常用的字節碼生成器的類庫,它提供了一系列API實現java字節碼的生成和轉換功能。我們在學習JDK的動態代理時都知道,JDK的動態代理只能針對接口,如果一個類沒有實現任何接口,要對其進行動態代理只能使用CGLIB。
我們已經分析了容器初始化生成Bean所包含的Java實例對象的過程,現在我們繼續分析生成對象后,Spring IoC容器是如何將Bean的屬性依賴關系注入Bean實例對象中並設置好的,屬性依賴注入的代碼如下:
1 //將Bean屬性設置到生成的實例對象上
2 protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) {
3 //獲取容器在解析Bean定義資源時為BeanDefiniton中設置的屬性值
4 PropertyValues pvs = mbd.getPropertyValues();
5 //實例對象為null
6 if (bw == null) {
7 //屬性值不為空
8 if (!pvs.isEmpty()) {
9 throw new BeanCreationException(
10 mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
11 }
12 else {
13 //實例對象為null,屬性值也為空,不需要設置屬性值,直接返回
14 return;
15 }
16 }
17 //在設置屬性之前調用Bean的PostProcessor后置處理器
18 boolean continueWithPropertyPopulation = true;
19 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
20 for (BeanPostProcessor bp : getBeanPostProcessors()) {
21 if (bp instanceof InstantiationAwareBeanPostProcessor) {
22 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
23 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
24 continueWithPropertyPopulation = false;
25 break;
26 }
27 }
28 }
29 }
30 if (!continueWithPropertyPopulation) {
31 return;
32 }
33 //依賴注入開始,首先處理autowire自動裝配的注入
34 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
35 mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
36 MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
37 //對autowire自動裝配的處理,根據Bean名稱自動裝配注入
38 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
39 autowireByName(beanName, mbd, bw, newPvs);
40 }
41 //根據Bean類型自動裝配注入
42 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
43 autowireByType(beanName, mbd, bw, newPvs);
44 }
45 pvs = newPvs;
46 }
47 //檢查容器是否持有用於處理單態模式Bean關閉時的后置處理器
48 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
49 //Bean實例對象沒有依賴,即沒有繼承基類
50 boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
51 if (hasInstAwareBpps || needsDepCheck) {
52 //從實例對象中提取屬性描述符
53 PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw);
54 if (hasInstAwareBpps) {
55 for (BeanPostProcessor bp : getBeanPostProcessors()) {
56 if (bp instanceof InstantiationAwareBeanPostProcessor) {
57 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
58 //使用BeanPostProcessor處理器處理屬性值
59 pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
60 if (pvs == null) {
61 return;
62 }
63 }
64 }
65 }
66 if (needsDepCheck) {
67 //為要設置的屬性進行依賴檢查
68 checkDependencies(beanName, mbd, filteredPds, pvs);
69 }
70 }
71 //對屬性進行注入
72 applyPropertyValues(beanName, mbd, bw, pvs);
73 }
74 //解析並注入依賴屬性的過程
75 protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
76 if (pvs == null || pvs.isEmpty()) {
77 return;
78 }
79 //封裝屬性值
80 MutablePropertyValues mpvs = null;
81 List<PropertyValue> original;
82 if (System.getSecurityManager()!= null) {
83 if (bw instanceof BeanWrapperImpl) {
84 //設置安全上下文,JDK安全機制
85 ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
86 }
87 }
88 if (pvs instanceof MutablePropertyValues) {
89 mpvs = (MutablePropertyValues) pvs;
90 //屬性值已經轉換
91 if (mpvs.isConverted()) {
92 try {
93 //為實例化對象設置屬性值
94 bw.setPropertyValues(mpvs);
95 return;
96 }
97 catch (BeansException ex) {
98 throw new BeanCreationException(
99 mbd.getResourceDescription(), beanName, "Error setting property values", ex);
100 }
101 }
102 //獲取屬性值對象的原始類型值
103 original = mpvs.getPropertyValueList();
104 }
105 else {
106 original = Arrays.asList(pvs.getPropertyValues());
107 }
108 //獲取用戶自定義的類型轉換
109 TypeConverter converter = getCustomTypeConverter();
110 if (converter == null) {
111 converter = bw;
112 }
113 //創建一個Bean定義屬性值解析器,將Bean定義中的屬性值解析為Bean實例對象
114 //的實際值
115 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
116 //為屬性的解析值創建一個拷貝,將拷貝的數據注入到實例對象中
117 List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
118 boolean resolveNecessary = false;
119 for (PropertyValue pv : original) {
120 //屬性值不需要轉換
121 if (pv.isConverted()) {
122 deepCopy.add(pv);
123 }
124 //屬性值需要轉換
125 else {
126 String propertyName = pv.getName();
127 //原始的屬性值,即轉換之前的屬性值
128 Object originalValue = pv.getValue();
129 //轉換屬性值,例如將引用轉換為IoC容器中實例化對象引用
130 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
131 //轉換之后的屬性值
132 Object convertedValue = resolvedValue;
133 //屬性值是否可以轉換
134 boolean convertible = bw.isWritableProperty(propertyName) &&
135 !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
136 if (convertible) {
137 //使用用戶自定義的類型轉換器轉換屬性值
138 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
139 }
140 //存儲轉換后的屬性值,避免每次屬性注入時的轉換工作
141 if (resolvedValue == originalValue) {
142 if (convertible) {
143 //設置屬性轉換之后的值
144 pv.setConvertedValue(convertedValue);
145 }
146 deepCopy.add(pv);
147 }
148 //屬性是可轉換的,且屬性原始值是字符串類型,且屬性的原始類型值不是
149 //動態生成的字符串,且屬性的原始值不是集合或者數組類型
150 else if (convertible && originalValue instanceof TypedStringValue &&
151 !((TypedStringValue) originalValue).isDynamic() &&
152 !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
153 pv.setConvertedValue(convertedValue);
154 deepCopy.add(pv);
155 }
156 else {
157 resolveNecessary = true;
158 //重新封裝屬性的值
159 deepCopy.add(new PropertyValue(pv, convertedValue));
160 }
161 }
162 }
163 if (mpvs != null && !resolveNecessary) {
164 //標記屬性值已經轉換過
165 mpvs.setConverted();
166 }
167 //進行屬性依賴注入
168 try {
169 bw.setPropertyValues(new MutablePropertyValues(deepCopy));
170 }
171 catch (BeansException ex) {
172 throw new BeanCreationException(
173 mbd.getResourceDescription(), beanName, "Error setting property values", ex);
174 }
}
對屬性的注入過程分以下兩種情況:
(1).屬性值類型不需要轉換時,不需要解析屬性值,直接准備進行依賴注入。
(2).屬性值需要進行類型轉換時,如對其他對象的引用等,首先需要解析屬性值,然后對解析后的屬性值進行依賴注入。
對屬性值的解析是在BeanDefinitionValueResolver類中的resolveValueIfNecessary方法中進行的,對屬性值的依賴注入是通過bw.setPropertyValues方法實現的,在分析屬性值的依賴注入之前,我們先分析一下對屬性值的解析過程。
1 //解析屬性值,對注入類型進行轉換
2 public Object resolveValueIfNecessary(Object argName, Object value) {
3 //對引用類型的屬性進行解析
4 if (value instanceof RuntimeBeanReference) {
5 RuntimeBeanReference ref = (RuntimeBeanReference) value;
6 //調用引用類型屬性的解析方法
7 return resolveReference(argName, ref);
8 }
9 //對屬性值是引用容器中另一個Bean名稱的解析
10 else if (value instanceof RuntimeBeanNameReference) {
11 String refName = ((RuntimeBeanNameReference) value).getBeanName();
12 refName = String.valueOf(evaluate(refName));
13 //從容器中獲取指定名稱的Bean
14 if (!this.beanFactory.containsBean(refName)) {
15 throw new BeanDefinitionStoreException(
16 "Invalid bean name '" + refName + "' in bean reference for " + argName);
17 }
18 return refName;
19 }
20 //對Bean類型屬性的解析,主要是Bean中的內部類
21 else if (value instanceof BeanDefinitionHolder) {
22 BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
23 return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
24 }
25 else if (value instanceof BeanDefinition) {
26 BeanDefinition bd = (BeanDefinition) value;
27 return resolveInnerBean(argName, "(inner bean)", bd);
28 }
29 //對集合數組類型的屬性解析
30 else if (value instanceof ManagedArray) {
31 ManagedArray array = (ManagedArray) value;
32 //獲取數組的類型
33 Class elementType = array.resolvedElementType;
34 if (elementType == null) {
35 //獲取數組元素的類型
36 String elementTypeName = array.getElementTypeName();
37 if (StringUtils.hasText(elementTypeName)) {
38 try {
39 //使用反射機制創建指定類型的對象
40 elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
41 array.resolvedElementType = elementType;
42 }
43 catch (Throwable ex) {
44 throw new BeanCreationException(
45 this.beanDefinition.getResourceDescription(), this.beanName,
46 "Error resolving array type for " + argName, ex);
47 }
48 }
49 //沒有獲取到數組的類型,也沒有獲取到數組元素的類型,則直接設置數
50 //組的類型為Object
51 else {
52 elementType = Object.class;
53 }
54 }
55 //創建指定類型的數組
56 return resolveManagedArray(argName, (List<?>) value, elementType);
57 }
58 //解析list類型的屬性值
59 else if (value instanceof ManagedList) {
60 return resolveManagedList(argName, (List<?>) value);
61 }
62 //解析set類型的屬性值
63 else if (value instanceof ManagedSet) {
64 return resolveManagedSet(argName, (Set<?>) value);
65 }
66 //解析map類型的屬性值
67 else if (value instanceof ManagedMap) {
68 return resolveManagedMap(argName, (Map<?, ?>) value);
69 }
70 //解析props類型的屬性值,props其實就是key和value均為字符串的map
71 else if (value instanceof ManagedProperties) {
72 Properties original = (Properties) value;
73 //創建一個拷貝,用於作為解析后的返回值
74 Properties copy = new Properties();
75 for (Map.Entry propEntry : original.entrySet()) {
76 Object propKey = propEntry.getKey();
77 Object propValue = propEntry.getValue();
78 if (propKey instanceof TypedStringValue) {
79 propKey = evaluate((TypedStringValue) propKey);
80 }
81 if (propValue instanceof TypedStringValue) {
82 propValue = evaluate((TypedStringValue) propValue);
83 }
84 copy.put(propKey, propValue);
85 }
86 return copy;
87 }
88 //解析字符串類型的屬性值
89 else if (value instanceof TypedStringValue) {
90 TypedStringValue typedStringValue = (TypedStringValue) value;
91 Object valueObject = evaluate(typedStringValue);
92 try {
93 //獲取屬性的目標類型
94 Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
95 if (resolvedTargetType != null) {
96 //對目標類型的屬性進行解析,遞歸調用
97 return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
98 }
99 //沒有獲取到屬性的目標對象,則按Object類型返回
100 else {
101 return valueObject;
102 }
103 }
104 catch (Throwable ex) {
105 throw new BeanCreationException(
106 this.beanDefinition.getResourceDescription(), this.beanName,
107 "Error converting typed String value for " + argName, ex);
108 }
109 }
110 else {
111 return evaluate(value);
112 }
113 }
114 //解析引用類型的屬性值
115 private Object resolveReference(Object argName, RuntimeBeanReference ref) {
116 try {
117 //獲取引用的Bean名稱
118 String refName = ref.getBeanName();
119 refName = String.valueOf(evaluate(refName));
120 //如果引用的對象在父類容器中,則從父類容器中獲取指定的引用對象
121 if (ref.isToParent()) {
122 if (this.beanFactory.getParentBeanFactory() == null) {
123 throw new BeanCreationException(
124 this.beanDefinition.getResourceDescription(), this.beanName,
125 "Can't resolve reference to bean '" + refName +
126 "' in parent factory: no parent factory available");
127 }
128 return this.beanFactory.getParentBeanFactory().getBean(refName);
129 }
130 //從當前的容器中獲取指定的引用Bean對象,如果指定的Bean沒有被實例化
131 //則會遞歸觸發引用Bean的初始化和依賴注入
132 else {
133 Object bean = this.beanFactory.getBean(refName);
134 //將當前實例化對象的依賴引用對象
135 this.beanFactory.registerDependentBean(refName, this.beanName);
136 return bean;
137 }
138 }
139 catch (BeansException ex) {
140 throw new BeanCreationException(
141 this.beanDefinition.getResourceDescription(), this.beanName,
142 "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
143 }
144 }
145 //解析array類型的屬性
146 private Object resolveManagedArray(Object argName, List<?> ml, Class elementType) {
147 //創建一個指定類型的數組,用於存放和返回解析后的數組
148 Object resolved = Array.newInstance(elementType, ml.size());
149 for (int i = 0; i < ml.size(); i++) {
150 //遞歸解析array的每一個元素,並將解析后的值設置到resolved數組中,索引為i
151 Array.set(resolved, i,
152 resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
153 }
154 return resolved;
155 }
156 //解析list類型的屬性
157 private List resolveManagedList(Object argName, List<?> ml) {
158 List<Object> resolved = new ArrayList<Object>(ml.size());
159 for (int i = 0; i < ml.size(); i++) {
160 //遞歸解析list的每一個元素
161 resolved.add(
162 resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
163 }
164 return resolved;
165 }
166 //解析set類型的屬性
167 private Set resolveManagedSet(Object argName, Set<?> ms) {
168 Set<Object> resolved = new LinkedHashSet<Object>(ms.size());
169 int i = 0;
170 //遞歸解析set的每一個元素
171 for (Object m : ms) {
172 resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), m));
173 i++;
174 }
175 return resolved;
176 }
177 //解析map類型的屬性
178 private Map resolveManagedMap(Object argName, Map<?, ?> mm) {
179 Map<Object, Object> resolved = new LinkedHashMap<Object, Object>(mm.size());
180 //遞歸解析map中每一個元素的key和value
181 for (Map.Entry entry : mm.entrySet()) {
182 Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey());
183 Object resolvedValue = resolveValueIfNecessary(
184 new KeyedArgName(argName, entry.getKey()), entry.getValue());
185 resolved.put(resolvedKey, resolvedValue);
186 }
187 return resolved;
188 }
通過上面的代碼分析,我們明白了Spring是如何將引用類型,內部類以及集合類型等屬性進行解析的,屬性值解析完成后就可以進行依賴注入了,依賴注入的過程就是Bean對象實例設置到它所依賴的Bean對象屬性上去,在第7步中我們已經說過,依賴注入是通過bw.setPropertyValues方法實現的,該方法也使用了委托模式,在BeanWrapper接口中至少定義了方法聲明,依賴注入的具體實現交由其實現類BeanWrapperImpl來完成,下面我們就分析依BeanWrapperImpl中賴注入相關的源碼。BeanWrapperImpl類主要是對容器中完成初始化的Bean實例對象進行屬性的依賴注入,即把Bean對象設置到它所依賴的另一個Bean的屬性中去,依賴注入的相關源碼如下:
1 //實現屬性依賴注入功能
2 private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
3 //PropertyTokenHolder主要保存屬性的名稱、路徑,以及集合的size等信息
4 String propertyName = tokens.canonicalName;
5 String actualName = tokens.actualName;
6 //keys是用來保存集合類型屬性的size
7 if (tokens.keys != null) {
8 //將屬性信息拷貝
9 PropertyTokenHolder getterTokens = new PropertyTokenHolder();
10 getterTokens.canonicalName = tokens.canonicalName;
11 getterTokens.actualName = tokens.actualName;
12 getterTokens.keys = new String[tokens.keys.length - 1];
13 System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
14 Object propValue;
15 try {
16 //獲取屬性值,該方法內部使用JDK的內省( Introspector)機制,調用屬性//的getter(readerMethod)方法,獲取屬性的值
17 propValue = getPropertyValue(getterTokens);
18 }
19 catch (NotReadablePropertyException ex) {
20 throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
21 "Cannot access indexed value in property referenced " +
22 "in indexed property path '" + propertyName + "'", ex);
23 }
24 //獲取集合類型屬性的長度
25 String key = tokens.keys[tokens.keys.length - 1];
26 if (propValue == null) {
27 throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
28 "Cannot access indexed value in property referenced " +
29 "in indexed property path '" + propertyName + "': returned null");
30 }
31 //注入array類型的屬性值
32 else if (propValue.getClass().isArray()) {
33 //獲取屬性的描述符
34 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
35 //獲取數組的類型
36 Class requiredType = propValue.getClass().getComponentType();
37 //獲取數組的長度
38 int arrayIndex = Integer.parseInt(key);
39 Object oldValue = null;
40 try {
41 //獲取數組以前初始化的值
42 if (isExtractOldValueForEditor()) {
43 oldValue = Array.get(propValue, arrayIndex);
44 }
45 //將屬性的值賦值給數組中的元素
46 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
47 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
48 Array.set(propValue, arrayIndex, convertedValue);
49 }
50 catch (IndexOutOfBoundsException ex) {
51 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
52 "Invalid array index in property path '" + propertyName + "'", ex);
53 }
54 }
55 //注入list類型的屬性值
56 else if (propValue instanceof List) {
57 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
58 //獲取list集合的類型
59 Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
60 pd.getReadMethod(), tokens.keys.length);
61 List list = (List) propValue;
62 //獲取list集合的size
63 int index = Integer.parseInt(key);
64 Object oldValue = null;
65 if (isExtractOldValueForEditor() && index < list.size()) {
66 oldValue = list.get(index);
67 }
68 //獲取list解析后的屬性值
69 Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
70 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
71 if (index < list.size()) {
72 //為list屬性賦值
73 list.set(index, convertedValue);
74 }
75 //如果list的長度大於屬性值的長度,則多余的元素賦值為null
76 else if (index >= list.size()) {
77 for (int i = list.size(); i < index; i++) {
78 try {
79 list.add(null);
80 }
81 catch (NullPointerException ex) {
82 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
83 "Cannot set element with index " + index + " in List of size " +
84 list.size() + ", accessed using property path '" + propertyName +
85 "': List does not support filling up gaps with null elements");
86 }
87 }
88 list.add(convertedValue);
89 }
90 }
91 //注入map類型的屬性值
92 else if (propValue instanceof Map) {
93 PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
94 //獲取map集合key的類型
95 Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
96 pd.getReadMethod(), tokens.keys.length);
97 //獲取map集合value的類型
98 Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
99 pd.getReadMethod(), tokens.keys.length);
100 Map map = (Map) propValue;
101 //解析map類型屬性key值
102 Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType,
103 new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType));
104 Object oldValue = null;
105 if (isExtractOldValueForEditor()) {
106 oldValue = map.get(convertedMapKey);
107 }
108 //解析map類型屬性value值
109 Object convertedMapValue = convertIfNecessary(
110 propertyName, oldValue, pv.getValue(), mapValueType,
111 new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1)));
112 //將解析后的key和value值賦值給map集合屬性
113 map.put(convertedMapKey, convertedMapValue);
114 }
115 else {
116 throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
117 "Property referenced in indexed property path '" + propertyName +
118 "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
119 }
120 }
121 //對非集合類型的屬性注入
122 else {
123 PropertyDescriptor pd = pv.resolvedDescriptor;
124 if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
125 pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
126 //無法獲取到屬性名或者屬性沒有提供setter(寫方法)方法
127 if (pd == null || pd.getWriteMethod() == null) {
128 //如果屬性值是可選的,即不是必須的,則忽略該屬性值
129 if (pv.isOptional()) {
130 logger.debug("Ignoring optional value for property '" + actualName +
131 "' - property not found on bean class [" + getRootClass().getName() + "]");
132 return;
133 }
134 //如果屬性值是必須的,則拋出無法給屬性賦值,因為每天提供setter方法異常
135 else {
136 PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
137 throw new NotWritablePropertyException(
138 getRootClass(), this.nestedPath + propertyName,
139 matches.buildErrorMessage(), matches.getPossibleMatches());
140 }
141 }
142 pv.getOriginalPropertyValue().resolvedDescriptor = pd;
143 }
144 Object oldValue = null;
145 try {
146 Object originalValue = pv.getValue();
147 Object valueToApply = originalValue;
148 if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
149 if (pv.isConverted()) {
150 valueToApply = pv.getConvertedValue();
151 }
152 else {
153 if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
154 //獲取屬性的getter方法(讀方法),JDK內省機制
155 final Method readMethod = pd.getReadMethod();
156 //如果屬性的getter方法不是public訪問控制權限的,即訪問控制權限比較嚴格,
157 //則使用JDK的反射機制強行訪問非public的方法(暴力讀取屬性值)
158 if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
159 !readMethod.isAccessible()) {
160 if (System.getSecurityManager()!= null) {
161 //匿名內部類,根據權限修改屬性的讀取控制限制
162 AccessController.doPrivileged(new PrivilegedAction<Object>() {
163 public Object run() {
164 readMethod.setAccessible(true);
165 return null;
166 }
167 });
168 }
169 else {
170 readMethod.setAccessible(true);
171 }
172 }
173 try {
174 //屬性沒有提供getter方法時,調用潛在的讀取屬性值//的方法,獲取屬性值
175 if (System.getSecurityManager() != null) {
176 oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
177 public Object run() throws Exception {
178 return readMethod.invoke(object);
179 }
180 }, acc);
181 }
182 else {
183 oldValue = readMethod.invoke(object);
184 }
185 }
186 catch (Exception ex) {
187 if (ex instanceof PrivilegedActionException) {
188 ex = ((PrivilegedActionException) ex).getException();
189 }
190 if (logger.isDebugEnabled()) {
191 logger.debug("Could not read previous value of property '" +
192 this.nestedPath + propertyName + "'", ex);
193 }
194 }
195 }
196 //設置屬性的注入值
197 valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd);
198 }
199 pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
200 }
201 //根據JDK的內省機制,獲取屬性的setter(寫方法)方法
202 final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
203 ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
204 pd.getWriteMethod());
205 //如果屬性的setter方法是非public,即訪問控制權限比較嚴格,則使用JDK的反射機制,
206 //強行設置setter方法可訪問(暴力為屬性賦值)
207 if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
208 //如果使用了JDK的安全機制,則需要權限驗證
209 if (System.getSecurityManager()!= null) {
210 AccessController.doPrivileged(new PrivilegedAction<Object>() {
211 public Object run() {
212 writeMethod.setAccessible(true);
213 return null;
214 }
215 });
216 }
217 else {
218 writeMethod.setAccessible(true);
219 }
220 }
221 final Object value = valueToApply;
222 if (System.getSecurityManager() != null) {
223 try {
224 //將屬性值設置到屬性上去
225 AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
226 public Object run() throws Exception {
227 writeMethod.invoke(object, value);
228 return null;
229 }
230 }, acc);
231 }
232 catch (PrivilegedActionException ex) {
233 throw ex.getException();
234 }
235 }
236 else {
237 writeMethod.invoke(this.object, value);
238 }
239 }
240 catch (TypeMismatchException ex) {
241 throw ex;
242 }
243 catch (InvocationTargetException ex) {
244 PropertyChangeEvent propertyChangeEvent =
245 new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
246 if (ex.getTargetException() instanceof ClassCastException) {
247 throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
248 }
249 else {
250 throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
251 }
252 }
253 catch (Exception ex) {
254 PropertyChangeEvent pce =
255 new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
256 throw new MethodInvocationException(pce, ex);
257 }
258 }
}
通過對上面注入依賴代碼的分析,我們已經明白了Spring IoC容器是如何將屬性的值注入到Bean實例對象中去的:
(1).對於集合類型的屬性,將其屬性值解析為目標類型的集合后直接賦值給屬性。
(2).對於非集合類型的屬性,大量使用了JDK的反射和內省機制,通過屬性的getter方法(reader method)獲取指定屬性注入以前的值,同時調用屬性的setter方法(writer method)為屬性設置注入后的值。看到這里相信很多人都明白了Spring的setter注入原理
三總結

注入過程


