IOC容器的初始化分爲三個步驟
- Resource定位,即BeanDefinition的資源定位。
- BeanDefinition的載入
- 向IOC容器註冊BeanDefinition
1,Resource定位
以ApplicationContext的具體實現FileSystemXmlApplicationContext來介紹Resource定位的過程:
IOC容器初始化類比爲用木桶來裝水,Resource的定位過程就是尋找水的過程。
它是由ResourceLoader通過統一的Resource接口來完成的,Resource對各種形式的BeanDefinition的使用都提供了統一的接口
Resource接口有許多實現類,針對不同的BeanDefinition,如:
在文件系統中的Bean定義信息可以使用FileSystemResource來進行抽象。
在類路徑中的Bean定義信息可以使用ClassPathResource來進行抽象。
我們來看下FileSystemXmlApplicationContext其中的一個構造函數:
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
這裏有個**refresh()**方法,這個方法非常重要,可以說是IOC容器啓動的入口,該方法的實現在AbstractApplicationContext中。
在AbstractApplicationContext的refresh方法中,最終對調用到AbstractRefreshableApplicationContext的refreshBeanFactory,在這裏會創建一個基礎的IOC容器供ApplicationContext使用,這個基礎的BeanFactory就是DefaultListableBeanFactory。
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);
}
}
再根據loadBeanDefinitions方法一直往下查找,最終會找到DefaultResourceLoader類的getResource方法:
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new UrlResource(url);
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
這裏的getResourceByPath方法最終被子類重寫,該場景下重寫該方法的類就是FileSystemXmlApplicationContext
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
這樣我們從FileSystemXmlApplicationContext的構造函數中的refresh方法開始,最終到getResourceByPath結束,完成了資源定位的解析。但是這個只是容器啓動中的一部分,還有載入和解析也是糅合在一起的,只是爲了思路清晰,故意對這些地方視而不見。
2,BeanDefinition的載入和解析
在第一部分資源的定位中,我們是以getResourceByPath()結束的,接下來我們要通過該方法返回的Resource對象來進行BeanDefinition的載入了。現在我們已經知道水在哪裏了,就可以現在打水和裝水之旅了。
這個過程就是將定義的BeanDefinition在IOC容器中轉化成一個Spring內部表示的數據結構的過程。我們緊接着前面的源碼往下梳理:
AbstractRefreshableApplicationContext的方法refreshBeanFactory中調用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);
}
其中第7行是爲讀取器設置ResourceLoader,爲後面的資源讀取做準備;第13行就是啓動Bean定義信息載入的開始。
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
第2行是以Resource的方式獲取配置文件的資源位置,而第6行是以String的形式獲取配置文件的位置。
reader.loadBeanDefinitions()的實現見XmlBeanDefinitionReader的父類AbstractBeanDefinitionReader
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int counter = 0;
for (String location : locations) {
counter += loadBeanDefinitions(location);
}
return counter;
}
這裏如果Resource爲空,則停止BeanDefinition的載入。在啓動BeanDefinition的過程中,會遍歷整個Resource集合所包含的BeanDefinition的信息。
這裏面調用的loadBeanDefinitions()方法具體實現並不在AbstractBeanDefinitionReader,而是在子類裏:
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();
}
}
在這裏可以拿到代表XML文件的Resource,讀取器在打開I/O流後就可以得到XML的文件對象,接下來的事情就是按照Spring的Bean定義規則對這個XML文件做解析並封裝了。而這個解析的過程是在類BeanDefinitionParserDelegate
在調用doLoadBeanDefinitions過程中,代碼會走到類XmlBeanDefinitionReader中的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);
}
這裏第5行就是Document對象生成的入口,具體實現在DefaultDocumentLoader中。
第7行就是BeanDefinition解析的入口,我們接着往下走,最終的解析過程在類BeanDefinitionParserDelegate中,源碼如下:
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<String>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
其中 第24行會觸發對Bean元素的詳細解析,解析完成後會返回一個AbstractBeanDefinition對象,可以看下這個對象的屬性,基本上都是Spring配置文件中的常用屬性
解析方法的具體內容如下:
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
try {
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
其中第18行-27行,都是對Spring配置文件中不同節點的解析,可以每個都深入去研究下。最終返回一個AbstractBeanDefinition對象。
到這裏,XML文件中定義的BeanDefinition就被整個載入到IOC容器中,建立了對應的數據結構,可以看成是POJO在容器中的抽象。但是這個時候容器中還只是有一些靜態的配置信息,完成了管理Bean對象的數據準備工作,但是容器還沒有完全發揮作用。
3,BeanDefinition註冊過程
這個源碼中方法調用過程比較簡單,我們直接來看註冊的核心代碼:
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
synchronized (this.beanDefinitionMap) {
Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
if (!this.allowBeanDefinitionOverriding) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
}
else {
this.beanDefinitionNames.add(beanName);
this.frozenBeanDefinitionNames = null;
}
this.beanDefinitionMap.put(beanName, beanDefinition);
resetBeanDefinition(beanName);
}
}
最關鍵的一步就是第36行,所謂的註冊就是將解析得到的BeanDefinition設置到hashMap中去。至此就完成了整個IOC容器初始化的工作,這樣一來就可以在beanDefinition裏檢索和使用已經配置好的Bean了。ICO容器的作用就是維護和處理裏面的Bean。
最後,我們來回答下這個問題,spring 容器中bean是什麼時候被初始化的?
通過前面的分析,我們知道bean的實例化是伴隨着容器的初始化而同時進行的(但是也有特例),並且默認情況下是單例的