Spring原理(一)IoC容器的初始化过程之BeanFactory

时间:2022-12-22 19:49:13
  1. IoC容器的初始化过程
    IoC容器的启动过程包括BeanDefinition的Resource定位、载入和注册三个基本过程。
    但spring是把这三个过程分开的,并用不同的模块来完成,比如ResourceLoader、
    BeanDefinitionReader、这种设计具有很高的灵活性,用户可以根据不同的需要组合出适合自己的初始
    化过程。
    第一个过程是Resource定位。即BeanDefinition资源的定位,spring定义了一个Resource接口来定
    义资源,ResourceLoader负责资源的定位。Spring支持多种Resource如下图,
    Spring原理(一)IoC容器的初始化过程之BeanFactory
    如果把IoC容器的初始化过程比作一个人在沙漠里找水的话,Resource定位就相当于找到沙漠中的水源。
    第二个过程是BeanDefinition的载入。这个过程就是把用户卸载配置文件中的bean表示成IoC容器内
    的数据结构,即BeanDefinition。通过BeanDefinition这个数据结构IoC容器能够方便的对POJO对
    象也就是Bean进行管理。BeanDefinition的载入分为两个过程,首先通过调用XML的解析器得到
    Document对象,但这些Document对象并没有按照spring定义的bean的规则进行解析;然后
    DocumentReader按照spring定义的bean的规则进行解析,默认的DocumentReader是
    DefaultBeanDefinitionDocumentReader。
    第三个过程是向IoC容器注册这些BeanDefinition。载入的BeanDefinition最终是通过一个HashMap来持有的,因此注册也就是把解析得到的BeanDefinition设置到HashMap中去。通过实现BeanDefinitionRegistry接口的方法registerBeanDefinition来注册BeanDefinition。
  2. 源码分析
    这里以编程方式初始化DefaultListableBeanFactory为例。
    1)Resource定位
    //这里以类路径类型的资源为例,根据上面介绍还可以用其他类型的资源
    ClassPathResource res = new ClassPathResource(“applicationContext.xml”);
    这里的Resource并不能被IoC容器直接使用,需要解析成IOC容器能够理解的数据类型,即
    BeanDefinition,spring通过BeanDefinitionReader来对Resource信息进行处理。因为
    DefaultListableBeanFactory从名字上可以看出来,它是一个纯粹的IoC容器(这里注意和
    applicationContext的区别,即非纯粹的IoC容器,或者叫高级IoC容器,在BeanFactory的基础上附加
    了很多功能,比如这里设置的读取器),因此需要为它配置特定的读取器。
    2)Resource加载和解析
    第一步找到了水源,这一步就要实体查看一下,水源有很多种,特别是在沙漠,有点水就可以救命啊,什么仙人掌上的露珠,只剩井底小水坑的枯井,沙漠小绿洲,甚至神秘的地下河(电影里的情节),根据不同的水源把水取到手才是最重要的,这里加载Resource非常类似。
    这里使用编程的方式初始化一个纯粹的IoC容器,即DefaultListableBeanFactory,并把它设置到XmlBeanDefinitionReader 中,因为DefaultListableBeanFactory实现了BeanDefinitionRegistry的方法registerBeanDefinition,这个方法用于注册BeanDefinition,在第三步会详细介绍。
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);

XmlBeanDefinitionReader的loadBeanDefinitions是实现了接口BeanDefinitionReader的
loadBeanDefinitions(Resource resource)方法(这里有一个模板的设计模式,但使用这种编程的方式初始化纯粹的IoC容器并未体现,下文分析applicationContext初始化的时候会进一步说明)

public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}

然后调用下面XmlBeanDefinitionReader自己的loadBeanDefinitions

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();
}
}
}

doLoadDocument获取XML文件的Document对象,这里使用的是默认的DocumentLoader

       private DocumentLoader documentLoader = new DefaultDocumentLoader();

registerBeanDefinitions方法启动对Document的解析按照spring定义的bean规则(看方法名字容易产生歧义,认为这是注册BeanDefinition的方法,其实不然,个人感觉这个命名不太合适,很容易产生误解,特别是对第一次读源码的菜鸟)

            protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource);
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);
}
}

整个Document对象的解析都是由BeanDefinitionDocumentReader 负责,createBeanDefinitionDocumentReader创建解析BeanDefinition的文档读取器,具体的解析过程由registerBeanDefinitions方法完成。

    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
documentReader.setEnvironment(getEnvironment());
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}

这里设置了一个readerContext,用于最后一步注册BeanDefinition,会在第三步详细说明
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}

protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);

if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
return;
}
}
}

preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);

this.delegate = parent;
}

parseDefaultElement真正对Document对象的元素进行解析

    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}

下面是解析不同的spring配置文件不同标签的逻辑

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}

在方法parseBeanDefinitionElement里会去实例化配置文件中配置的bean,注意看异常处理部分,我们平时经常遇到的Bean class not found的错误是在这里暴露出来的。

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;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}

return null;
}

3)Resource注册
一条小河出现在眼前,主角喜极而泣,奔到河边,狂喝一顿,突然想起了快渴死的同伴,于是装满水壶带回去,拯救了同伴,而且后面的行程,想喝就喝。接下来要发生的事情何其类似。
BeanDefinition加载完成之后,要把它注册到IoC容器中,其实就是把bean对象添加到一个HashMap中,BeanDefinitionReaderUtils.registerBeanDefinition方法完成注册。
这里getReaderContext得到的readerContext是之前步骤中已经设置好的,即DefaultListableBeanFactory,他实现了BeanDefinitionRegistry的方法registerBeanDefinition,最终完成BeanDefinition的注册。

    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
**BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());**
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
    public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {

// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String aliase : aliases) {
registry.registerAlias(beanName, aliase);
}
}
}
    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);
}
}

BeanDefinition oldBeanDefinition;

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 (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (this.logger.isWarnEnabled()) {
this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
" with a framework-generated bean definition ': replacing [" +
oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
else {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
}
else {
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
this.frozenBeanDefinitionNames = null;
}
this.beanDefinitionMap.put(beanName, beanDefinition);

if (oldBeanDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}

到此为止,最基本IoC容器的初始化的过程的脉络已经显现出来了。下一篇会在此基础上介绍高级容器ApplicationContext的初始化过程。