【spring】源码-spring 容器启动过程之 AbstractXmlApplicationContext (三)

目录

方法一: prepareRefresh()方法

方法二:obtainFreshBeanFactory() 代码注释如下

  1.refreshBeanFactory()

   1.1 createBeanFactory()

   1.2 customizeBeanFactory(beanFactory)

   1.3 loadBeanDefinitions(beanFactory) 四个实现类

         1.AbstractXmlApplicationContext 

         2. AnnotationConfigWebApplicationContext 注解配置

         3. GroovyWebApplicationContext

         4.  XmlWebApplicationContext


      经过一系列准备工作 ,都是为了接下来refresh()方法的实现,此方法spring只在AbstractApplicationContext 类中提供全套实现,定义了容器中bean 的加载流程,看到其他类中的refresh(),都是调用这里的;

 

首先代码如下,我将分别阅读每个方法;

public void refresh() throws BeansException, IllegalStateException {
		//startupShutdownMonitor 同步锁
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			//1、调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识
			prepareRefresh();


			//2、告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从子类的refreshBeanFactory()方法启动,获得一个新的beanfactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			//3、为BeanFactory配置容器特性,例如类加载器、事件处理器等
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//4、为容器的某些子类指定特殊的BeanPost事件处理器
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//5、调用所有注册的BeanFactoryPostProcessor的Bean
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//6、为BeanFactory注册BeanPost事件处理器.
				//BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//7、初始化信息源,和国际化相关.
				initMessageSource();

				// Initialize event multicaster for this context.
				//8、初始化容器事件传播器.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//9、调用子类的某些特殊Bean初始化方法
				onRefresh();

				// Check for listener beans and register them.
				//10、为事件传播器注册事件监听器.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//11、初始化所有剩余的单例Bean
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				//12、初始化容器的生命周期事件处理器,并发布容器的生命周期事件
				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.
				//13、销毁已创建的Bean
				destroyBeans();

				// Reset 'active' flag.
				//14、取消refresh操作,重置容器的同步标识。
				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...
				//15、重设公共缓存
				resetCommonCaches();
			}
		}
	}

设计到的类

     ConfigurableListableBeanFactory 接口 :ListableBeanFactory,ConfigurableBeanFactory,AutowireCapableBeanFactory 的子接口,

          ListableBeanFactory :提供了枚举所有 bean 实例的 方法,而不是提供名称去定向寻找;

          ConfigurableBeanFactory:被大多数的 bean 工厂 实现的 配置接口,提供 了用于配置 bean 工厂 的 基础设施;

          AutowireCapableBeanFactory: BeanFactory 的直接子接口,是 BeanFactory 的 扩展接口,能够实现自动装配;

依赖图:

需要记住这张图的依赖关系  ,可以帮助理解;

 

 

synchronized (this.startupShutdownMonitor) 

spring 保证在多线程的情况下 保证刷新和销毁操作不能同时进行,避免冲突错误。startupShutdownMonitor 只能一个线程持有对象锁,

没有加到外层refresh 方法上 是涉及到锁的粒度的问题(缩小同步的范围),粒度越小,性能越好;

 

方法一: prepareRefresh()方法

protected void prepareRefresh() {
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);//设置容器状态为未关闭
		this.active.set(true);// 设置容器活跃 状态

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}

		//调用父类方法 初始化5个环境对象
		initPropertySources();

		// 判断是否否是null
		getEnvironment().validateRequiredProperties();

		// Allow for the collection of early ApplicationEvents,
		//初始化事件多播器
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}//东方鲤鱼

   主要作用:

    1.设置一下刷新Spring上下文的开始时间

   2.  将active标识位设置为true

   3. 获取资源属性,并验证是否为空

   4. 向容器注册事件监听器

我们利用debug m模式调试看一initPropertySources方法内部,可以看到方法内调用了本类的方法还是我们上一步的方法,生成默认的五个配置,如下图

 

 

方法二:obtainFreshBeanFactory() 代码注释如下

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的refreshBeanFactory()方法
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}东方鲤鱼

此方法是为了获得刷新spring 上下文的beanFactory ;方法中refreshBeanFactory() h很重要;spring 中一共有两个类实现了此方法,分别是AbstractRefreshableApplicationContext 类,GenericApplicationContext类,GenericApplicationContext 类中判断是否已经完成,没有默认生成一个DefaultListableBeanFactory 返回;我们主要看 AbstractRefreshableApplicationContext.refreshBeanFactory() 方法;如下

  1.refreshBeanFactory()

加载xml配置文件,创建Spring Bean Definition 解析出来的数据转换为Definition  对象

protected final void refreshBeanFactory() throws BeansException {
		//如果已经有容器,销毁容器中的bean,关闭容器
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			//创建IOC容器
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			//对IOC容器进行定制化,如设置启动参数,开启注解的自动装配等
			customizeBeanFactory(beanFactory);
			//调用载入Bean定义的方法,主要这里又使用了一个委派模式,在当前类中只定义了抽象的loadBeanDefinitions方法,具体的实现调用子类容器
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}东方鲤鱼

   1.1 createBeanFactory()

    这时候我们看到 这行代码,(重要  重要 重要)

	//创建IOC容器
	DefaultListableBeanFactory beanFactory = createBeanFactory();

        createBeanFactory() 方法 最终返回一个 DefaultListableBeanFactory 对象,这个DefaultListableBeanFactory  Bean工厂类,内部存储了bean definition信息,即bean的元数据,即描述bean的信息,这些内容存放在DefaultListableBeanFactory内的不同的容器中(map、list、set),记住这个类,尤其是内部的对象,我们分别介绍一下

---------------------------对象属性介绍------------------------
BeanDefinition每个bean对象都会生成一个BeanDefinition对象,内部维护可bean 相关的的所有信息
 aliasMap别名映射表
singletonObjects  存储单例Bean名称->单例Bean实现映射关系
earlySingletonObjects 存储Bean名称->预加载Bean实现映射关系 
beanDefinitionMap存储Bean名称->Bean定义信息映射关系 
private volatile List<String> beanDefinionNames = new ArrayList<>(256);
存储Bean定义名称列表 
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

存储修正过的依赖映射关系 

resolvableDependencies依赖注入类
ignoredDependencyTypes忽略自动注入的类型
ignoredDependencyInterfaces忽略自动注入的接口
allowCircularReferences是否允许bean之间存在循环依赖
allowBeanDefinitionOverriding是否允许覆盖同名称的不同定义的对象

带着这些概念进入createBeanFactory方法内部

protected DefaultListableBeanFactory createBeanFactory() {
        return new DefaultListableBeanFactory(this.getInternalParentBeanFactory());
    }
东方鲤鱼

看到是直接实例化DefaultListableBeanFactory 类返回,返回信息看上边的debug截图;

 

接着然后把webApplicationcontext  的contextId设置非beanFactory  的serializationId ,如果需要的话,让这个BeanFactory从id反序列化到BeanFactory对象;

接着往下看

   1.2 customizeBeanFactory(beanFactory)

    这个方法的作用是spring 提供的子类扩展,我们可以自定义bean工厂的一些策略;

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
		// 如果属性allowBeanDefinitionOverriding不为空,设置给beanFactory对象相应属性
        // 表示是否允许重写beanDifinition 
		if (this.allowBeanDefinitionOverriding != null) {
			beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		//  如果属性allowCircularReferences不为空,设置给beanFactory对象相应属性
         // 标表示是否允许对象循环依赖
		if (this.allowCircularReferences != null) {
			beanFactory.setAllowCircularReferences(this.allowCircularReferences);
		}
	}东方鲤鱼

 这两属性allowCircularReferences   allowBeanDefinitionOverriding 在 DefaultListableBeanFactory  类中定义 ,在上边的断点中也可以看到,所有第一次进来默认都为null;

我们可以自定义beanfactory ,通过继承AbstractXmlApplicationContext 类来设置属性,演示代码如下

   1.3 loadBeanDefinitions(beanFactory) 四个实现类

      先了解BeanDefinitions 的整体设计

东方鲤鱼

     

  这个方法是入参也是创建出来的 DefaultListableBeanFactory 对象,内部就是给DefaultListableBeanFactory 对象设置 所有bean  Definition 属性;此方法采用模板方法设计,所有实现交给子类不同实现,一共有四个类实现了这个抽象方法,分别如下:

         1.AbstractXmlApplicationContext 

               AbstractXmlApplicationContext  类是   ClassPathXmlApplicationContext 与 FileSystemXmlApplicationContext 类的父类 , 所以加载xml 就是通过委派这两个类来实现的, 主要作用是容器启动过程中,主动获取程序需要注入的bean 文件解析,j如下图

                                               

             AbstractXmlApplicationContext  类中有实现了父类的抽象方法loadBeanDefinitions(DefaultListableBeanFactory beanFactory)    如下

	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		//创建XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容  器使用该读取器读取Bean定义资源
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
		
		//为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的
		//祖先父类AbstractApplicationContext继承DefaultResourceLoader,子类使用父类属性
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		//为Bean读取器设置xml解析器
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
		
		//当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制
		initBeanDefinitionReader(beanDefinitionReader);
		//Bean读取器真正实现加载的方法
		loadBeanDefinitions(beanDefinitionReader);
	}
东方鲤鱼

             解释:  方法主要 通过实例化资源加载器 并配置spring相关资源解析器等属性 然后执行 initBeanDefinitionReader(beanDefinitionReader) 方法开始读取容器中的xml 资源  ,XmlBeanDefinitionReader 类  是spring 中定义用来资源文件的读取、解析即注册 ,继续往下看 initBeanDefinitionReader(beanDefinitionReader) 方法  ,内部主要是设置是否开启对xml 的验证;所有操作都是给BeanDefinitionReader对象加载BeanDefinitioin对象做准备工作;接着来看看 loadBeanDefinitions(beanDefinitionReader)  方法  ,此方法才是真正的 对xml  读取、解析即注册  ;方法如下:

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//获取Bean定义资源的定位
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
			//的Bean定义资源
			reader.loadBeanDefinitions(configResources);
		}
		//如果子类中获取的Bean定义资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
			//的Bean定义资源
			reader.loadBeanDefinitions(configLocations);
		}
	}东方鲤鱼

       解释:getConfigResources() 用来获取程序启动读取的xml ,内部实现交给子类ClassPathXmlApplicationContext 来实现的,spring 中的资源如果是非硬盘上存储的资源,统一都需要用Resource 类包装,Resource是顶层抽象接口提供了足够的抽象,提供了很多内置Resource实现:ByteArrayResource、InputStreamResource 、FileSystemResource 、UrlResource 、ClassPathResource等实现类,分别实现了对URL资源、File资源资源、ClassPath相关资源的流 化处理以及 转化方法,spring 有完整的一套资源处理机制 ,这里不细化了;ClassPathXmlApplicationContext 类中实现为:


	@Nullable
	private Resource[] configResources;

	@Override
	@Nullable
	protected Resource[] getConfigResources() {
		return this.configResources;
	}


public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			//重启、刷新、重置
			refresh();
		}
	}

            解释:原理就是 子类调用父类的方法把程序中定义的xml 资源刷新到容器中; refresh() 方法之前讲了  全局只会在 AbstractApplicationContext 类中实现,这里也是调用超级父类重复之前的逻辑;

         而 getConfigLocations()   是通过FileSystemXmlApplicationContext 类加载的资源 ,实现方式类 也是调用超级父类的; refresh() 方法 

     区别:

         ClassPathXmlApplicationContext  :默认文件路径是src下资源, classpath*: 可以加载多个配置文件,如果有多个配置文件;

         FileSystemXmlApplicationContext:加载默认获取的是项目路径 (没有盘符的情况)。如果前边加了file:则说明后边的路径就要写绝对路径  例如 file:D:/workspace/demo/src/applicationContext.xml(有盘符的情况); 

到此,文件的读取工作完成,进入XmlBeanDefinitionReader类的loadBeanDefinitions()方法来看如何解析,XmlBeanDefinitionReader 是实现父类BeanDefinitionReader 接口的方法

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		//获取在IoC容器初始化过程中设置的资源加载器
		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 {
				//将指定位置的Bean定义资源文件解析为Spring IOC容器封装的资源
				//加载多个指定位置的Bean定义资源文件
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				//委派调用其子类XmlBeanDefinitionReader的方法,实现加载功能
				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.
			//将指定位置的Bean定义资源文件解析为Spring IOC容器封装的资源
			//加载单个指定位置的Bean定义资源文件
			Resource resource = resourceLoader.getResource(location);
			//委派调用其子类XmlBeanDefinitionReader的方法,实现加载功能
			int loadCount = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
			}
			return loadCount;
		}
	}

	//重载方法,调用loadBeanDefinitions(String);
	@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;
	}东方鲤鱼

        解析: 首先从Ioc 容器中获取设置的资源加载器,,使用BeanDefinitionReader对象所持有的ResourceLoader来生成Resource对象。然后调用BeanDefinitionReader的loadBeanDefinitions(Resource… resources)或者loadBeanDefinitions(Resource resource)方法来执行加载BeanDefinition的代码,其中,判断资源加载器是 resourceLoader与子类ResourcePatternResolverd的关系,主要目的判断是否发生子类重载过方法,分别执行不同逻辑,前一个方法通过多个资源文件来加载,后一个方法通过一个资源文件来加载。

上图中的 重载方法 在父类AbstractBeanDefinitionReader中有实现,XmlBeanDefinitionReader直接继承了它而已;
 此处需要明白这几个类的关系:

                                                                 

           

   

    先看处理多个Resource对象的loadBeanDefinitions(Resource… resources)方法, XmlBeanDefinitionReader 实现如下:

      

@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		//将读入的XML资源进行特殊编码处理
		return loadBeanDefinitions(new EncodedResource(resource));
	}
	


	//这里是载入XML形式Bean定义资源文件方法
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<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			//将资源文件转为InputStream的IO流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				//从InputStream中得到XML的解析源
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				//这里是具体的读取过程
				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
			}
			finally {
				//关闭从Resource中得到的IO流
				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();
			}
		}
	}东方鲤鱼

  解析:从Resource对象中获取xml文件输入流,并用它来创建InputSource对象。然后调用XmlBeanDefinitionReader的doLoadBeanDefinitions(InputSource inputSource, Resource resource)方法,

//从特定XML文件中实际载入Bean定义资源的方法
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
			//将XML文件转换为DOM对象,解析过程由documentLoader实现
			Document doc = doLoadDocument(inputSource, resource);
			//这里是启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则
			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);
		}
	} //东方鲤鱼

内部方法 doLoadDocument(InputSource inputSource, Resource resource)

//获得document 对象
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
		return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
				getValidationModeForResource(resource), isNamespaceAware());
	}
	
	// 获得xml xsd验证模式
	protected int getValidationModeForResource(Resource resource) {
		int validationModeToUse = getValidationMode();
		if (validationModeToUse != VALIDATION_AUTO) {
			return validationModeToUse;
		}
		int detectedMode = detectValidationMode(resource);
		if (detectedMode != VALIDATION_AUTO) {
			return detectedMode;
		}
		// Hmm, we didn't get a clear indication... Let's assume XSD,
		// since apparently no DTD declaration has been found up until
		// detection stopped (before finding the document's root tag).
		return VALIDATION_XSD;
	}东方鲤鱼

      解析:先是获取xml文档的验证模式,spring使用的xsd模式;然后调用DocumentLoader的loadDocument来读取InputSource对象中的XML内容并创建Document对象,XmlBeanDefinitionReader默认的DocumentLoader为DefaultDocumentLoader;最后调用registerBeanDefinitions(Document doc, Resource resource)方法来处理刚创建的Document对象;

	//按照Spring的Bean语义要求将Bean定义资源解析并转换为容器内部数据结构
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//获得BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		//获得容器中注册的Bean数量
		int countBefore = getRegistry().getBeanDefinitionCount();
		//解析过程入口,这里使用了委派模式,BeanDefinitionDocumentReader只是个接口,
		//具体的解析实现过程有实现类DefaultBeanDefinitionDocumentReader完成
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		
		//统计解析的Bean数量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}东方鲤鱼

     解析:上图代码 XmlBeanDefinitionReader使用BeanDefinitionDocumentReader 对象来加载Document对象中的配置信息;

               第一步是创建BeanDefinitionDocumentReader对象,默认是DefaultBeanDefinitionDocumentReader 注册的;

              第二步是创建调用它的registerBeanDefinitions方法所需要的XmlReaderContext上下文对象,XmlReaderContext对象持有当前要读取的资源、xml命名空间处理;   createReaderContext(resource) 方法内部如下       

	//创建BeanDefinitionDocumentReader对象,解析Document对象
	protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
		return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
	}
	//创建 XmlReaderContext 设置 对象所有上下文
	public XmlReaderContext createReaderContext(Resource resource) {
		return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
				this.sourceExtractor, this, getNamespaceHandlerResolver());
	}
	// 创建NamespaceHandlerResolver对象
	public NamespaceHandlerResolver getNamespaceHandlerResolver() {
		if (this.namespaceHandlerResolver == null) {
			this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver();
		}
		return this.namespaceHandlerResolver;
	}
	//创建命名空间处理器
	protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
		ClassLoader cl = (getResourceLoader() != null ? getResourceLoader().getClassLoader() : getBeanClassLoader());
		return new DefaultNamespaceHandlerResolver(cl);
	}东方鲤鱼

              第三步是调用documentReader的registerBeanDefinitions(Document doc, XmlReaderContext readerContext)处理Document对象。此方法交给具体实现类实现父类BeanDefinitionDocumentReader中定义的接口;

        

    //根据Spring DTD对Bean的定义规则解析Bean定义Document对象
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		//获得XML描述符
		this.readerContext = readerContext;
		logger.debug("Loading bean definitions");
		//获得Document的根元素
		Element root = doc.getDocumentElement();
		doRegisterBeanDefinitions(root);
	}

	protected void doRegisterBeanDefinitions(Element root) {
		//具体的解析过程由BeanDefinitionParserDelegate实现,
		//BeanDefinitionParserDelegate中定义了Spring Bean定义XML文件的各种元素
		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)) {
					if (logger.isInfoEnabled()) {
						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		//在解析Bean定义之前,进行自定义的解析,增强解析过程的可扩展性
		preProcessXml(root);
		//从Document的根元素开始进行Bean定义的Document对象
		parseBeanDefinitions(root, this.delegate);
		//在解析Bean定义之后,进行自定义的解析,增加解析过程的可扩展性
		postProcessXml(root);

		this.delegate = parent;
	}

解析:以上是对获取到的xml document 做解析,XML文件中只允许有一个根节点,上面的代码所做的事情就是保存XmlReaderContext 对象并提取根节点,然后调用DefaultBeanDefinitionDocumentReader的doRegisterBeanDefinitions(Element root)方法,其中BeanDefinitionParserDelegate 中定义的素有xml 中的元素标签;以上所有的步骤最终就是要解析根据spring 的标签规则解析xml  转化为Definition 对象 并注册到DefinitionMap 中,同时销毁以前旧的对象这些事情;

   preProcessXml(root) 方法是spring 可扩展方法,可以用来增强一些自定义功能;这个方法会在 parseBeanDefinitions() 前后各执行一次,目的是在解析前执行防止存在自定义解析,然后当执行完解析后再执行一次看有没有自定义,保证可以在解析bean 前后执执行到;

    parseBeanDefinitions()方法 如下

	//使用Spring的Bean规则从Document的根元素开始进行Bean定义的Document对象
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		//Bean定义的Document对象使用了Spring默认的XML命名空间
		if (delegate.isDefaultNamespace(root)) {
			//获取Bean定义的Document对象根元素的所有子节点
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				//获得Document节点是XML元素节点
				if (node instanceof Element) {
					Element ele = (Element) node;
					//Bean定义的Document的元素节点使用的是Spring默认的XML命名空间
					if (delegate.isDefaultNamespace(ele)) {
						//使用Spring的Bean规则解析元素节点
						parseDefaultElement(ele, delegate);
					}
					else {
						//没有使用Spring默认的XML命名空间,则使用用户自定义的解//析规则解析元素节点
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			//Document的根节点没有使用Spring默认的命名空间,则使用用户自定义的
			//解析规则解析Document根节点
			delegate.parseCustomElement(root);
		}
	}
东方鲤鱼

解析:这段代码主要是区分节点的命名空间,根据不同命名空间,调用相应的方法。如果节点在默认命名空间,则调用DefaultBeanDefinitionDocumentReader的parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate)方法,否则调用BeanDefinitionParserDelegate 的parseCustomElement(Element ele)方法

//使用Spring的Bean规则解析Document元素节点
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		//如果元素节点是<Import>导入元素,进行导入解析
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		//如果元素节点是<Alias>别名元素,进行别名解析
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		//元素节点既不是导入元素,也不是别名元素,即普通的<Bean>元素,
		//按照Spring的Bean规则解析元素
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			//  处理beans节点元素,递归调用doRegisterBeanDefinitions
			doRegisterBeanDefinitions(ele);
		}
	}
东方鲤鱼

    解析:处理默认命名空间下的节点;

            importBeanDefinitionResource(ele) 方法是 如果元素节点是<Import>导入元素,进行导入解析 ,一般为配置文件;

             processAliasRegistration(ele) 方法是如果元素节点是<Alias>别名元素,进行别名解析,alias标签是为一个已定义了的bean取别名,它的name属性值是bean的id,alias属性值是要取的别名,多个别名用英文逗号、分号或者空格隔开;

            processBeanDefinition(ele, delegate)方法元素节点既不是导入元素,也不是别名元素,即普通的<Bean>元素, 按照Spring的Bean规则解析元素,一般此标签表示要实例化的对象;

             doRegisterBeanDefinitions(ele)方法  处理beans节点元素,递归调用doRegisterBeanDefinitions,上边见过此方法  调用自身来递归遍历; 多环节区分;

      这四个方法的任务就是按照规则解析xml 资源,完成后向容器发布存管事件;

       其中了解一下      processBeanDefinition(ele, delegate)方法 中解析完后bean definition 注册过程;

   

//解析Bean定义资源Document对象的普通元素
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		// BeanDefinitionHolder是对BeanDefinition的封装,即Bean定义的封装类
		//对Document对象中<Bean>元素的解析由BeanDefinitionParserDelegate实现
		// BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				//向Spring IOC容器注册解析得到的Bean定义,这是Bean定义向IOC容器注册的入口
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			//在完成向Spring IOC容器注册解析得到的Bean定义之后,发送注册事件
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}东方鲤鱼
//将解析的BeanDefinitionHold注册到容器中
	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// Register bean definition under primary name.
		//获取解析的BeanDefinition的名称
		String beanName = definitionHolder.getBeanName();
		//向IOC容器注册BeanDefinition
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		//如果解析的BeanDefinition有别名,向容器为其注册别名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}东方鲤鱼

 

	//向IOC容器注册解析的BeanDefiniton
	@Override
	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");

		//校验解析的BeanDefiniton
		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 (!isAllowBeanDefinitionOverriding()) {
				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 (!beanDefinition.equals(oldBeanDefinition)) {
				if (this.logger.isInfoEnabled()) {
					this.logger.info("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + oldBeanDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (this.logger.isDebugEnabled()) {
					this.logger.debug("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + oldBeanDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				//注册的过程中需要线程同步,以保证数据的一致性
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					if (this.manualSingletonNames.contains(beanName)) {
						Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
						updatedSingletons.remove(beanName);
						this.manualSingletonNames = updatedSingletons;
					}
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				this.manualSingletonNames.remove(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		//检查是否有同名的BeanDefinition已经在IOC容器中注册
		if (oldBeanDefinition != null || containsSingleton(beanName)) {
			//重置所有已经注册过的BeanDefinition的缓存
			resetBeanDefinition(beanName);
		}
	}东方鲤鱼

       解析:这就是beanDifinition 的注册过程,调用代理对象的parseBeanDefinitionElement(Element ele)方法创建BeanDefinitionHolder 对象,这个对象持有创建好的BeanDefinition对象、bean的id和bean的别名,接着调用代理对象的decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder)来对BeanDefinition对象进一步处理,主要是解析bean标签中自定义属性和自定义标签,最后调用工具类BeanDefinitionReaderUtils的registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)方法,这个方法用于注册创建好的BeanDefinition;注意注册的过程是同步操作,以保证数据的一致性;

到此,xml 的读取  解析  注册基本完成;

         2. AnnotationConfigWebApplicationContext 注解配置

               该类也是AbstractRefreshableWebApplicationContext的子类,主要基于注解配置方式来实现bean 的定义;(文章过长不方便阅读,单独编写一篇;)

         3. GroovyWebApplicationContext

             基于Groovy 项目的开发使用;

         4.  XmlWebApplicationContext

              该类也是AbstractRefreshableWebApplicationContext的子类,主要是解析web工程定制的方法,推荐Web项目中使用;对指定xml文件进行解析操作,解析的过程和AbstractXmlApplicationContext 类一样;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东方鲤鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值