Spring容器创建流程(2)创建beanFactory,加载BeanDefinition

Spring 容器的创建。obtainFreshBeanFactorr()中完成容器的创建。(BeanFactory关系类图,之前的执行流程可在本系列博客中看到)。接下来看容器创建的第二部,创建beanFactory


容器refresh总览:

		synchronized (this.startupShutdownMonitor) {
			// 设置环境,校验参数。
			prepareRefresh();
			
			// 创建BeanFactory(DefaultListableBeanFactor),加载bean定义信息。
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}

obtainFreshBeanFactory 容器创建

容器初始化refresh方法中 obtainFreshBeanFactory用来创建容器实例

// AbstractApplicationContext中,重要的方法是refreshBeanFactory()方法
// getBeanFactory()不过是直接获取创建好的工厂
		protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}

refreshBeanFactory()

refreshBeanFactory 方法在 AbstractApplicationContext的子类AbstractRefreshableApplicationContext中实现。

BeanDefinition: 是包含着类的定义信息,类的名字,作用域,是否懒加载等等描述bean的信息(也就是xml中配置的bean信息的封装)

	@Override
	protected final void refreshBeanFactory() throws BeansException {
		// 如果工厂已经创建,销毁工厂
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			// 直接创建一个DefaultListableBeanFactory工厂
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			// 交给子类自定义配置
			customizeBeanFactory(beanFactory);
			// 加载beanDefinition
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

AbstractRefreshableApplicationContext 中对 customizeBeanFactory的实现

	protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
	// 是否允许bean定义覆盖(默认不允许)
		if (this.allowBeanDefinitionOverriding != null) {
			beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
	// 是否允许循环依赖(默认不允许)
		if (this.allowCircularReferences != null) {
			beanFactory.setAllowCircularReferences(this.allowCircularReferences);
		}
	}

loadBeanDefinitions(beanFactory);

创建工厂中最重要的一步,加载bean的定义信息。

首先明确几个概念

  1. XXXResource:代表着资源文件
  2. XXXBeanDefinitionReader: 用于读取Resource,
  3. BeanDefinition: bean的描述信息,也就是xml中bean配置的描述的封装
	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// beanFactory本身是一个BeanDefinitionRegistry,用于注册bean信息
		// 创建 reader 读取 resource
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// 设置资源加载环境
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		// 设置资源加载器,beanFactory也实现了ResourceLoader,用于将制定位置的资源,加载为Resource
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// 给子类一个再次设置的机会
		initBeanDefinitionReader(beanDefinitionReader);
		// 加载bean定义信息
		loadBeanDefinitions(beanDefinitionReader);
	}
	
	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		// 获取资源文件路径
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
		// 使用XmlBeanDefinitionReader加载资源
			reader.loadBeanDefinitions(configLocations);
		}
	}
XmlBeanDefinitionReader 加载 Resource
	@Override
	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;
	}
	@Override
	public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}

    // 最终调用这个方法
	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
	// 获取资源加载器,也就是前面注册的beanFactory(它就是一个资源加载器这里用的是ClassPathXmlApplicationContext)
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
			// 加载资源
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
			// 加载bean定义信息
				int loadCount = loadBeanDefinitions(resources);
				if (actualResources != null) {
					for (Resource resource : resources) {
						actualResources.add(resource);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
				}
				return loadCount;
			}
			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 loadCount = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
			}
			return loadCount;
		}
	}

Resource[] resources ((ResourcePatternResolver)resourceLoader).getResources(location);

// this.resourcePatternResolver 在构造器中已经初始化完成。
	@Override
	public Resource[] getResources(String locationPattern) throws IOException {
		return this.resourcePatternResolver.getResources(locationPattern);
	}

PathMarchingResourcePatternResolver获取资源

	@Override
	public Resource[] getResources(String locationPattern) throws IOException {
		Assert.notNull(locationPattern, "Location pattern must not be null");
		// 如果以 classpath*:开头
		if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
			// a class path resource (multiple resources for same name possible)
			// isPattern判断资源路径中是否包含* 或者 ?
			if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
				// a class path resource pattern
				return findPathMatchingResources(locationPattern);
			}
			else {
				// all class path resources with the given name
				return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
			}
		}
		else {
			// Generally only look for a pattern after a prefix here,
			// and on Tomcat only after the "*/" separator for its "war:" protocol.
			int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
					locationPattern.indexOf(':') + 1);
			if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
				// a file pattern
				return findPathMatchingResources(locationPattern);
			}
			else {
				// a single resource with the given name
				// 提供的资源路径是 classpath:application.xml 最终调用这里。
				// 路径封装为一个Resource
				return new Resource[] {getResourceLoader().getResource(locationPattern)};
			}
		}
	}

XmlBeanDefinitionReader 加载 Resource 已经完成,接下来就是使用Resource加载BeanDefinition。

XmlBeanDefinitionReader 加载BeanDefinition

AbstractBeanDefinitionReader.loadBeanDefinitions(String location, @Nullable Set actualResources) 方法中,getConfigResources()已经获取资源完毕。

// 加载资源
Resource[] configResources = getConfigResources();
// 加载bean定义信息
int loadCount = loadBeanDefinitions(resources);
	@Override
	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int counter = 0;
		for (Resource resource : resources) {
			counter += loadBeanDefinitions(resource);
		}
		return counter;
	}
	@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		// 统一编码封装
		return loadBeanDefinitions(new EncodedResource(resource));
	}

	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());
		}
// resourceCurrentlyBeingLoaded是一个ThreadLocal,存放线程开始加载的资源
		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流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
			// 包装为InputSource
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
			// 加载bean定义信息
				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 {
			// 使用dom解析文件
			Document doc = doLoadDocument(inputSource, resource);
			// 解析dom包装为beanDefinition,具体的解析过程比较复杂。
			// beanDefinitionRegistry就是上面的beanFactory,解析dom封装为beanDefinition后,保存到beanFactory中(就是调用beanDefinitionRegistry的registerBeanDefinition()方法)
			return registerBeanDefinitions(doc, resource);
		}
		....
	}

自此,beanFactory创建完成并且,beanDefinition也加载完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值