Spring源码解析正确姿势之IOC(1)

1.前言

上次写到 ClasspathXmlApplication类中的refresh中的主流程:
1.ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
2.this.postProcessBeanFactory(beanFactory);
3.this.invokeBeanFactoryPostProcessors(beanFactory);
4.this.finishBeanFactoryInitialization(beanFactory);

2.正文

/**
  * 1、创建BeanFactory对象
  * 2、解析Spring.xml
      传统标签解析:bean、import等
	  自定义标签解析 如:<context:component-scan base-package="xxx.xxx.xxx"/>
**/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

点入obtainFreshBeanFactory()

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //这个方法完成上述功能
	refreshBeanFactory();
	//这个方法返回了创建出来的BeanFactory对象
	return getBeanFactory();
}

点入refreshBeanFactory()
注意:这个方法是模版方法,有两个实现类分别是
1.AbstractRefreshableApplicationContext
2.GenericApplicationContext
这里进入的是1的方法

@Override
protected final void refreshBeanFactory() throws BeansException {
//对beanFactory做一些清理工作,如果BeanFactory不为空,就清理一下
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		//创建 beanFactory
		DefaultListableBeanFactory beanFactory = createBeanFactory();
	beanFactory.setSerializationId(getId());

//设置是否可以循环依赖对应的属性是allowCircularReferences
//是否允许使用相同名称重新注册不同的bean.
customizeBeanFactory(beanFactory);

		//解析xml,把xml中的<bean>封装成BeanDefinition对象,并把<compontScan>扫描的class封装成BeanDefinition对象
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor)  {
		//这里将beanFactory赋给成员变量,方便返回beanFactory对象
			this.beanFactory = beanFactory;
		}
	}
	catch (IOException ex) {
		throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}

这里对方法都做了注释,其中只看loadBeanDefinitions方法就行,这个方法做到类封装,收集BeanDefinition
属于核心方法,点入进去
注意:这个也是一个模版方法,其实现类有4个:
1.AbstractXmlApplicationContext
2.AnnotationConfigWebApplicationContext
3.GroovyWebApplicationContext
4.XmlWebApplicationContext
这里进入第一个

@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		//创建xml的解析器,这里是一个委托模式,委托模式很简单就是专人专事,这个模式我们平常就在用,比如service调用dao
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.getEnvironment());

		//这里传一个this进去,因为ApplicationContext是实现了ResourceLoader接口的
		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);
	}

点入loadBeanDefinitions(beanDefinitionReader);

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		//这个configLocations,我们前面提到过就是spring.xml
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
		//点入这个方法
			reader.loadBeanDefinitions(configLocations);
		}
}

点入这个方法
reader.loadBeanDefinitions(configLocations)

@Override
	public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
		Assert.notNull(locations, "Location array must not be null");
		int count = 0;
		//locations这个前面博客也说过,
		for (String location : locations) {
			count += loadBeanDefinitions(location);
		}
		return count;
	}

继续点入
count += loadBeanDefinitions(location);

@Override
	public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}

继续点入

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
				//将spring.xml,转换成Resource对象类型,其实就是用流的方式加载配置文件,然后封装成Resource对象,不重要,可以不看
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);

				//主要看这个方法 
				int count = loadBeanDefinitions(resources);
				if (actualResources != null) {
					Collections.addAll(actualResources, resources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
				}
				return count;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			int count = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
			}
			return count;
		}
}

继续点入
int count = loadBeanDefinitions(resources);

@Override
	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
			count += loadBeanDefinitions(resource);
		}
		return count;
	}

点入count += loadBeanDefinitions(resource);
注意:这里又是一个模版方法,其实现类有
1.GroovyBeanDefinitionReader
2.PropertiesBeanDefinitionReader
3.XmlBeanDefinitionReader
这里进入3

@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		//EncodedResource带编码的对Resource对象的封装
		return loadBeanDefinitions(new EncodedResource(resource));
	}

继续点入
loadBeanDefinitions(newEncodedResource(resource));

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isTraceEnabled()) {
			logger.trace("Loading XML bean definitions from " + encodedResource);
		}

		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
		if (currentResources == null) {
			currentResources = new HashSet<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			//获取Resource对象中的xml文件流对象
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				//InputSource是jdk中的sax xml文件解析对象
				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();
			}
		}
	}

终于点到正主了,大家会发现我们点入了好多loadBeanDefinitions,其实大家观察一下loadBeanDefinitions的参数,其实都不同。这里主要看doLoadBeanDefinitions(inputSource,encodedResource.getResource());其他一些方法已经做了注释,点进去

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			//把inputSource 封装成Document文件对象
			Document doc = doLoadDocument(inputSource, resource);

			//主要看这个方法,根据解析出来的document对象,拿到里面的节点封装成BeanDefinition
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		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);
		}
}

点入 int count = registerBeanDefinitions(doc,resource);

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//这里用到了委托,创建BeanDefinitionDocumentReader实例来解析document
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		//主要看这个方法,完成了beanDefinition对象的load
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

点入
documentReader.registerBeanDefinitions(doc,createReaderContext(resource));

@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		//主要看这个方法,把root节点传进去
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}

点入
doRegisterBeanDefinitions(doc.getDocumentElement());

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);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		preProcessXml(root);

		//主要看这个方法,标签具体解析过程
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}

点入 parseBeanDefinitions(root, this.delegate);

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

小结:
这篇文章就先总结到这里,下次接着说自定义标签解析和默认标签解析

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值