ClassPathXmlApplicationContext bean注册

概述
一、ClassPathXmlApplicationContext spring上下文,即容器,拥有注册器和bean工厂,调用refresh()方法,该方法最终调用loadBeanDefinitions(String location),然后将加载任务交由XmlBeanDefinitionReader;

二、XmlBeanDefinitionReader bean定义阅读器,拥有ClassPathXmlApplicationContext的bean注册器,使用DefaultBeanDefinitionDocumentReader解析xml文档,并将解析的标签交给BeanDefinitionParserDelegate解析。使用DefaultNamespaceHandlerResolver初始化命名空间处理器Map集合(映射规则在"META-INF/spring.handlers"中以键值对形式定义,各个处理器负责相应标签的解析,parse()方法)。

三、DefaultBeanDefinitionDocumentReader 文档阅读器,能解析xml文件,并将标签交由BeanDefinitionParserDelegate解析,执行doScan()等操作或生成beanDefinition并将beanDefinition注册到ClassPathXmlApplicationContext.beanFactory(因为这同时也是个注册器,作为参数一直在各个类中传递)

四、BeanDefinitionParserDelegate 若为自定义标签(除import、bean、alias、beans)根据标签的namespaceUri匹配NamespaceHandler,NamespaceHandler对标签执行parse()方法解析,若是bean标签则生成beanDefinition注册,否之执行其他操作。否则DefaultBeanDefinitionDocumentReader根据标签调用相应的方法。

  • ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
  • ClassPathXmlApplicationContext.refresh();
  • ConfigurableListableBeanFactory beanFactory = AbstractApplicationContext.obtainFreshBeanFactory();
  • AbstractApplicationContext.refreshBeanFactory();
  • AbstractRefreshableApplicationContext.refreshBeanFactory();
protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
                        //创建容器的bean工厂
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
                        //解析并注册bean
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}
  • AbstractXmlApplicationContext.loadBeanDefinitions(beanFactory)
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
                //XmlBeanDefinitionReader 此类加载DOM文档并将BeanDefinitionDocumentReader(实际为DefaultBeanDefinitionDocumentReader)应用于该文档。
                //BeanDefinitionDocumentReader解析文档后使用给定的beanFactory(DefaultListableBeanFactory,实现BeanDefinitionRegistry接口)注册bean,
                //即注册到beanFactory
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
                // environment为spring运行环境,包括一些运行参数等
		beanDefinitionReader.setEnvironment(this.getEnvironment());

                //ResourceLoader用来加载文件,如.class文件或其它系统文件,可根据路径获得资源抽象Resource和获得classLoader(用来搜索或加载类给jvm使用),
                //classLoader可知道包括当前运行环境中的class和package;
                //ClassPathXmlApplicationContext继承DefaultResourceLoader
		beanDefinitionReader.setResourceLoader(this);
                //ResourceEntityResolver 实现 EntityResolver,按照网上的资料,该类是用来查找.dtd约束文件或.schemas约束文件,
                //即定义application.xml时引入的约束文件,起规范配置内容的作用
		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);
                //加载bean定义,实际解析并注册动作
		loadBeanDefinitions(beanDefinitionReader);
	}
  • AbstractXmlApplicationContext.loadBeanDefinitions(beanDefinitionReader)
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
                //获取配置文件名application.xml,在构造方法中设置的
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
                         //加载bean定义
			reader.loadBeanDefinitions(configLocations);,
		}
	}
  • AbstractBeanDefinitionReader.loadBeanDefinitions(configLocations)
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
		Assert.notNull(locations, "Location array must not be null");
		int count = 0;
		for (String location : locations) {
                        //实际加载过程
			count += loadBeanDefinitions(location);
		}
		return count;
	}

public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}
  • AbstractBeanDefinitionReader.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");
		}
                //ApplicationContext接口实现ResourcePatternResolver接口
		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
                                //返回application.xml抽象实例
				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;
		}
	}
  • AbstractBeanDefinitionReader.loadBeanDefinitions(resources);
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
                        //加载bean定义
			count += loadBeanDefinitions(resource);
		}
		return count;
	}
  • XmlBeanDefinitionReader.loadBeanDefinitions(resource)
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
                //EncodedResource作用是以特定的encoding或Charset从资源中读取内容
		return loadBeanDefinitions(new EncodedResource(resource));
	}
  • XmlBeanDefinitionReader.loadBeanDefinitions(new EncodedResource(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 (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
                        //继续
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}
  • XmlBeanDefinitionReader.doLoadBeanDefinitions(inputSource, encodedResource.getResource())
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
                        //返回一个文档对象,该对象包含所有application.xml中配置的信息
			Document doc = doLoadDocument(inputSource, resource);
                        // 继续往下
			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(doc, resource)
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
                //创建文档阅读器,由上面可知为DefaultBeanDefinitionDocumentReader
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
                //获取注册前bean定义数目
		int countBefore = getRegistry().getBeanDefinitionCount();
                //解析注册bean定义
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}
//返回在bean定义读取过程中传递的上下文,封装了所有相关的配置和状态。包括阅读器[有注册器(DefaultListableBeanFactory)]、
//资源(Resource-application.xml)、名称空间处理器解析器(NamespaceHandlerResolver)等
public XmlReaderContext createReaderContext(Resource resource) {
                               //NamespaceHandlerResolver-DefaultNamespaceHandlerResolver根据映射文件中包含的映射将名称空间URI解析为实现类。
                               //映射规则在"META-INF/spring.handlers"中以键值对形式定义
                               //http://www.springframework.org/schema/context -> org.springframework.context.config.ContextNamespaceHandler
                               //相应的处理器定义了特定的标签如何解析
		return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
				this.sourceExtractor, this, getNamespaceHandlerResolver());
	}
  • DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(doc, createReaderContext(resource))
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
                //将根标签<beans></beans>作为参数执行解析注册
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}
  • DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(doc.getDocumentElement())
	@SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
	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;
	}
  • DefaultBeanDefinitionDocumentReader.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)) {
                                                //解析默认标签,import、bean、alias、beans
						parseDefaultElement(ele, delegate);
					}
					else {
                                                //其它标签
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}
  • DefaultBeanDefinitionDocumentReader.parseDefaultElement(ele, delegate) 解析默认标签
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
                 //<import></import>
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
                //<alias></alias>
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
                //<bean></bean>
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
                //<beans></beans>
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
  • BeanDefinitionParserDelegate.parseCustomElement(ele);解析自定义标签
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
                //查找,名称空间路径(每个标签具有的属性,直接获取)
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
                //通过路径匹配相应的处理器
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
                //调用处理器解析标签,执行相应的操作或生成bean定义,如    <context:component-scan base-package="com.jty.controller"/>,
                //则执行doScan方法扫描标注解的类然后注册,源代码如下
                //ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
		//Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
		//registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}
  • processBeanDefinition(ele, delegate); 解析bean标签
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
                //解析bean标签返回BeanDefinitionHolder,包含bean name、别名、BeanDefinition
                 //
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
                                //阅读器中的注册器将BeanDefinition注册到BeanDefinition Map,至此bean解析注册结束
				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));
		}
	}
  • BeanDefinitionParserDelegate.parseBeanDefinitionElement(ele)
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
                //获取标签id作为name
		String id = ele.getAttribute(ID_ATTRIBUTE);
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
                
               //解析别名
		List<String> aliases = new ArrayList<>();
		if (StringUtils.hasLength(nameAttr)) {
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = id;
		if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
			beanName = aliases.remove(0);
			if (logger.isTraceEnabled()) {
				logger.trace("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}

		if (containingBean == null) {
			checkNameUniqueness(beanName, aliases, ele);
		}
                
                //获取bean标签中class属性创建、初始化beanDefinition返回
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			if (!StringUtils.hasText(beanName)) {
				try {
					if (containingBean != null) {
						beanName = BeanDefinitionReaderUtils.generateBeanName(
								beanDefinition, this.readerContext.getRegistry(), true);
					}
					else {
						beanName = this.readerContext.generateBeanName(beanDefinition);
						// Register an alias for the plain bean class name, if still possible,
						// if the generator returned the class name plus a suffix.
						// This is expected for Spring 1.2/2.0 backwards compatibility.
						String beanClassName = beanDefinition.getBeanClassName();
						if (beanClassName != null &&
								beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
								!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
							aliases.add(beanClassName);
						}
					}
					if (logger.isTraceEnabled()) {
						logger.trace("Neither XML 'id' nor 'name' specified - " +
								"using generated bean name [" + beanName + "]");
					}
				}
				catch (Exception ex) {
					error(ex.getMessage(), ele);
					return null;
				}
			}
			String[] aliasesArray = StringUtils.toStringArray(aliases);
			return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
		}

		return null;
	}
原文地址:https://www.cnblogs.com/jinit/p/13871870.html