三、Spring源码学习之obtainFreshBeanFactory方法

obtainFreshBeanFactory()方法

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//创建Spring容器,解析xml 创建BeanDefinition,并且注册到Spring容器中
		refreshBeanFactory();
		//返回Spring容器
		return getBeanFactory();
}

AbstractRefreshableApplicationContext#refreshBeanFactory()方法

protected final void refreshBeanFactory() throws BeansException {
		//如果已经存在Spring容器
		if (hasBeanFactory()) {
			//则销毁容器中的bean
			destroyBeans();
			//关闭容器
			closeBeanFactory();
		}
		try {
			//创建Spring容器,这里使用的容器,默认实现DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			//设置容器id
			beanFactory.setSerializationId(getId());
			//指定一些特殊规则,一般不需要重写改方法
			customizeBeanFactory(beanFactory);
			//解析xml 创建BeanDefinition 并注册到Spring容器中
			loadBeanDefinitions(beanFactory);
			this.beanFactory = beanFactory;
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
}

DefaultSingletonBeanRegistry#destroySingletons()方法

//销毁所有单例bean
	public void destroySingletons() {
		if (logger.isTraceEnabled()) {
			logger.trace("Destroying singletons in " + this);
		}
		synchronized (this.singletonObjects) {
			this.singletonsCurrentlyInDestruction = true;
		}

		String[] disposableBeanNames;
		synchronized (this.disposableBeans) {
			disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
		}
		for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
			destroySingleton(disposableBeanNames[i]);
		}

		this.containedBeanMap.clear();
		this.dependentBeanMap.clear();
		this.dependenciesForBeanMap.clear();

		clearSingletonCache();
	}

	/**
	 * Clear all cached singleton instances in this registry.
	 * @since 4.3.15
	 * 清除一级,二级,三级缓存
	 */
	protected void clearSingletonCache() {
		synchronized (this.singletonObjects) {
			this.singletonObjects.clear();
			this.singletonFactories.clear();
			this.earlySingletonObjects.clear();
			this.registeredSingletons.clear();
			this.singletonsCurrentlyInDestruction = false;
		}
	}

AbstractXmlApplicationContext#loadBeanDefinitions()方法

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		//xml 转化为 对应 实体对象 的 解析器
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		//设置系统环境
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		//设置资源加载器
		beanDefinitionReader.setResourceLoader(this);
		//设置实体对象解析器 (主要作用是将xml中的bean标签解析成beanDefinition对象)
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		//设置XmlBeanDefinitionReader 其他的一些属性值,子类可重写该方法
		initBeanDefinitionReader(beanDefinitionReader);
		//解析xml,将bean注册到Spring容器中
		loadBeanDefinitions(beanDefinitionReader);
	}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//根据资源加载xml
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		//根据路径加载xml
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

AbstractBeanDefinitionReader#loadBeanDefinitions()方法

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
		Assert.notNull(locations, "Location array must not be null");
		int count = 0;//返回总注册bean的数量
		//遍历所有的路径加载xml
		for (String location : locations) {
			count += loadBeanDefinitions(location);
		}
		return count;
	}
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");
		}
		//这里的resourceLoader 就是ClassPathXmlApplicationContext 并且继承 ResourcePatternResolver
		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
				//根据路径获取路径中的资源
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				//加载资源,并返回注册bean的数量
				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;
		}
	}

XmlBeanDefinitionReader#loadBeanDefinitions()方法

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 {
			//获取资源的输入流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				//将输入流包装成source
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {//设置source的字符集
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				//正真开始解析xml
				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();
			}
		}
	}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			//将xml转成Document对象
			Document doc = doLoadDocument(inputSource, resource);
			//将document对象转成 beanDefinition,并且将其注册到Spring容器中
			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);
		}
	}

XmlBeanDefinitionReader#registerBeanDefinitions()方法

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//创建document转换beanDefinition解析器
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		//获取Spring容器中已经存在bean的数量
		int countBefore = getRegistry().getBeanDefinitionCount();
		//将document转换成beanDefinition 并且注册到Spring容器中
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		//返回新注册bean的数量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

DefaultBeanDefinitionDocumentReader#registerBeanDefinitions()方法

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		//开始转换,注册
		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.
		//真正处理从Document变为beanDefinition的类,解析各种标签
		BeanDefinitionParserDelegate parent = this.delegate;
		//创建解析beandefinition的处理类
		this.delegate = createDelegate(getReaderContext(), root, parent);
		//判断是否是默认命名空间
		if (this.delegate.isDefaultNamespace(root)) {
			//获取profile 指定使用那种环境下的xml
			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;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值