Spring 源码解析,配置文件的解析,Bean的注册(一)

原创
2019/10/18 14:52
阅读数 100

锁分析的jar包:spring-beans-3.2.5.RELEASE.jar

读取配置文件的方式
XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(new ClassPathResource("spring-test.xml"));
在spring 4.0中不推荐这种写法,换成:
ClassPathXmlApplicationContext content = new ClassPathXmlApplicationContext("classpath:spring-test.xml");
源码分析都差不多,

源码的核心:

1,DefaultListableBeanFactory 是注册和加载bean的默认实现,

2,XML解析

 2.1 XmlBeanDefinitionReader 是用来读取XML配置文件,在读取XML配置文件,Spring实际是将不同的资源路径抽象成URL,将配置文件封装为Resource的过程,看构造方法

// 获取配置文件路径,最终是转换成 ClassPathResource,而ClassPathResource这个类往上,继承AbstractFileResolvingResource继承AbstractResource,实现Resource接口
    public ClassPathResource(String path) {
        this(path, (ClassLoader)null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        String pathToUse = StringUtils.cleanPath(path);
        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }

        this.path = pathToUse;
        this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
    }

//创建XmlBeanFactory的过程
public class XmlBeanFactory extends DefaultListableBeanFactory {
	private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
	public XmlBeanFactory(Resource resource) throws BeansException {
		this(resource, null);
	}

    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
        //这个地方的super需要注意下,往上AbstractAutowireCapableBeanFactory里面构造方法调用了ignoreDependencyInterface()作用是忽略相应的依赖,
        super(parentBeanFactory);
		this.reader.loadBeanDefinitions(resource);
	}
}

类总结:主要是初始化。看ignoreDependencyInterface()方法的作用:自动装配忽略给定的依赖接口,举例当A中有属性B, 在获取A的bean,B如果没有被加载,那么spring 会自动初始化B,但某些情况下B不会被初始化。例如:B实现了BeanNameAware接口。自动装配忽略,典型应用是通过其他方式解析Application上下文注册依赖,类似于BeanFactory通过BeanNameAware进行注入或者ApplicationContext通过ApplicationContextAware进行注入。

2.2 具体来看 this.reader.loadBeanDefinitions(resource); 这个方法的实现

//上层方法主要将Resource转化为EncodedResource没做其他事,主要看这个方法
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<EncodedResource>(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 {
				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();
			}
		}
	}

//这个方法主要:1,判断文件类型。2,根据不同类型创建Document对象。3,交给下层方法
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
            //这个主要判断xml文件是DTD,还是XSD类型,
			int validationMode = getValidationModeForResource(resource);
            //根据获取的文件类型,转换成不用的Document对象
			Document doc = this.documentLoader.loadDocument(
					inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
            //注册bean定义
			return registerBeanDefinitions(doc, resource);
		}
     //....省略catch方法 
}

//这个方法作用:1,创建BeanDefinitionDocumentReader。2,初始化XmlReaderContext。3,交给子类实现
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
        //使用 DefaultBeanDefinitionDocumentReader实例化 BeanDefinitionDocumentReader
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		documentReader.setEnvironment(this.getEnvironment());
		int countBefore = getRegistry().getBeanDefinitionCount();
        //创建XmlReaderContext对象并初始化namespaceHandlerResolver为默认的DefaultNamespaceHandlerResolver,实现交给子类DefaultBeanDefinitionDocumentReader
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

解析XmlBeanDefinitionReader这个类主要做了

1,获取XML文件验证模式,

2,加载XML文件并获取Document对象,

3,初始化BeanDefinitionDocumentReader,并初始化XmlReaderContext,

 

2.3 看BeanDefinitionDocumentReader实现类DefaultBeanDefinitionDocumentReader,具体做了那些事情

//赋值readerContext,获取Document的element
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		logger.debug("Loading bean definitions");
		Element root = doc.getDocumentElement();
		doRegisterBeanDefinitions(root);
	}

//还是在判断各个参数
protected void doRegisterBeanDefinitions(Element root) {
       //处理profile属性
		String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
		if (StringUtils.hasText(profileSpec)) {
			Assert.state(this.environment != null, "Environment must be set for evaluating profiles");
			String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
					profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			if (!this.environment.acceptsProfiles(specifiedProfiles)) {
				return;
			}
		}
        //专门处理解析
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(this.readerContext, root, parent);

        //这里预留了空的方法,用户可以根据需求,解析前的处理
		preProcessXml(root);
        //主要看这个方法
		parseBeanDefinitions(root, this.delegate);
        //解析会的处理
		postProcessXml(root);

		this.delegate = parent;
	}

    //这个方法是判断是默认标签,还是自定义标签
    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);
		}
	}

    //解析四种标签,import,alias,bean,beans,
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
            //解析import标签
			importBeanDefinitionResource(ele);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
            //解析alias标签
			processAliasRegistration(ele);
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
            //bean标签的解析,
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse 解析beans
			doRegisterBeanDefinitions(ele);
		}
	}

看到这里,终于正式进入标签的解析,其中profile属性的作用可以同时在配置文件中部署两套配置来适用于生产环境和开发环境

总结类上主要做的事情,

1,获取所有标签,判断是默认标签还是自定义标签

2,解析属性,有自定义属性,再解析

3,bean标签的解析

配置文件中经常用到bean,我们主要看这个解析过程,看这个方法做了哪些事情:

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        //委托BeanDefinitionHolder类的parseBeanDefinitionElement方法进行元素解析并返回BeanDefinitionHolder,经过这个方法的处理,BeanDefinitionHolder已经包含了配置中的各个属性,例如:class,id,name,alias之类的属性
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
        //当BeanDefinitionHolder返回结果不为空,并且发现默认标签下面有自定义属性,在解析
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
                //通过beanName注册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.
            //发出响应事件,通知相关的监听器,这个bean已经加载完了,
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

3.1 默认属性的解析

看属性解析parseBeanDefinitionElement()

//parseBeanDefinitionElement() 这个方法主要传递了一个null的BeanDefinition对象,主要调用还在这
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
        //属性id, name解析
		String id = ele.getAttribute(ID_ATTRIBUTE);
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

		List<String> aliases = new ArrayList<String>();
		if (StringUtils.hasLength(nameAttr)) {
            //将nameAttr以 ,;中的任一或者组合来分割字符,不包含空字符
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}
        //将解析到的id作为beanName
		String beanName = id;
		if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
            //如果id属性为空,但有name属性,将name赋值给beanName
			beanName = aliases.remove(0);
			if (logger.isDebugEnabled()) {
				logger.debug("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}

		if (containingBean == null) {
            //解析beanName 的值是否有重名
			checkNameUniqueness(beanName, aliases, ele);
		}

        //创建AbstractBeanDefinition对象并且,将解析到的属性存在对象中
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			if (!StringUtils.hasText(beanName)) {
				try {
                    //如果beanName不存在,按照spring提供的命名规则生成beanName
					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.isDebugEnabled()) {
						logger.debug("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);
            //将获取到的bean信息封装到 BeanDefinitionHolder中
			return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
		}

		return null;
	}

以上就是对默认标签解析的全过程,主要做了以下内容:

1,提供标签的id, name属性,

2,创建AbstractBeanDefinition 对象并保存属性值,

3,检测beanName是否存在。

4,将获取到的信息封装到BeanDefinitionHolder

具体来看下抽象类AbstractBeanDefinition 的创建,它继承BeanDefinition接口,并有三种实现类,RootBeanDefinition, ChildBeanDefinition,GenericBeanDefinition,

RootBeanDefinition 是最常用的实现类,它对应一般性的bean 元素标签,

GenericBeanDefinition是自2.5版本后加入的bean文件配置属性定义类,

	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, BeanDefinition containingBean) {

		this.parseState.push(new BeanEntry(beanName));

		String className = null;
        //class属性的解析
		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}

		try {
			String parent = null;
            //parent属性的解析
			if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
				parent = ele.getAttribute(PARENT_ATTRIBUTE);
			}
            //创建GenericBeanDefinition 并用AbstractBeanDefinition来接收
			AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            //scope,singleton,abstract各种属性的解析
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

            //子元素meta标签的解析
			parseMetaElements(ele, bd);
            //子元素lookup的解析
			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
            //子元素replaceMethod解析
			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

            //子元素constructor-arg
			parseConstructorArgElements(ele, bd);
            //子元素property
			parsePropertyElements(ele, bd);
            //子元素quality
			parseQualifierElements(ele, bd);

			bd.setResource(this.readerContext.getResource());
			bd.setSource(extractSource(ele));

			return bd;
		} ... 省略catch

		return null;
	}

这个方法就是解析XM所有的标签及子元素,的属性,完成了从XML到GenericBeanDefinition对象的转化,GenericBeanDefinition只是子类实现,大部分属性都保存在AbstractBeanDefinition,

3.2 自定义属性的解析

decorateBeanDefinitionIfRequired()方法,如在XML中的申明:

<beans:bean id="student" class="com.study.Student" >
    <myBean:user username="aaa" />
</beans:bean>
// decorateBeanDefinitionIfRequired方法主要传递 null的BeanDefinition对象
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
			Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {

		BeanDefinitionHolder finalDefinition = definitionHolder;

		// Decorate based on custom attributes first.
		// 遍历所有属性,是否有适用于修饰的属性
		NamedNodeMap attributes = ele.getAttributes();
		for (int i = 0; i < attributes.getLength(); i++) {
			Node node = attributes.item(i);
			finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
		}

		// Decorate based on custom nested elements.
		// 遍历子节点
		NodeList children = ele.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
			}
		}
		return finalDefinition;
	}
//看decorateIfRequired 的实现
private BeanDefinitionHolder decorateIfRequired(
			Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) {
        //获取自定义标签的命名空间,上面示例的 myBean
		String namespaceUri = getNamespaceURI(node);
        //处理非默认的标签
		if (!isDefaultNamespace(namespaceUri)) {
            //根据命名空间找到处理器
			NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
			if (handler != null) {
                //进行修饰
				return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
			}
			else if (namespaceUri != null && namespaceUri.startsWith("http://www.springframework.org/")) {
				error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
			}
			else {
				// A custom namespace, not to be handled by Spring - maybe "xml:...".
				if (logger.isDebugEnabled()) {
					logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
				}
			}
		}
		return originalDef;
	}

首先获取属性或者标签的命名空间,判断如果是自定义标签进一步解析,这里基本就是自定义标签的解析,下一篇讲解,

这里decorateBeanDefinitionIfRequired对默认标签直接省略了,因为默认标签已经解析完了,

到这里对于配置文件,已经解析完了,BeanDefinition可以满足后续的要求,唯一剩下的就是注册

BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());

和发出响应事件,通知监听器

getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));

4,Bean的注册

注册分为两种:1,beanName的注册。2,alias别名注册

	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// Register bean definition under primary name.
		// 通过beanName的注册
		String beanName = definitionHolder.getBeanName();
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		// 通过别名的注册
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String aliase : aliases) {
				registry.registerAlias(beanName, aliase);
			}
		}
	}

4.1 beanName的注册

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

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
                //注册前的检测, 对于 AbstractBeanDefinition的methodOverrides校验
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

        //这里beanDefinitionMap 是全局会有并发的情况
		synchronized (this.beanDefinitionMap) {
			Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
			if (oldBeanDefinition != null) {
                //如果已经注册了,但不允许覆盖,会抛异常
				if (!this.allowBeanDefinitionOverriding) {
					throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
							"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
							"': There is already [" + oldBeanDefinition + "] bound.");
				}
				else {
                    //可以覆盖,日志记录
					if (this.logger.isInfoEnabled()) {
						this.logger.info("Overriding bean definition for bean '" + beanName +
								"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
					}
				}
			}
			else {
                // 记录beanName
				this.beanDefinitionNames.add(beanName);
				this.frozenBeanDefinitionNames = null;
			}
            //注册BeanDefinition
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
        //重置beanName,清除缓存
		resetBeanDefinition(beanName);
	}

	protected void resetBeanDefinition(String beanName) {
		// Remove the merged bean definition for the given bean, if already created.
		clearMergedBeanDefinition(beanName);

		// Remove corresponding bean from singleton cache, if any. Shouldn't usually
		// be necessary, rather just meant for overriding a context's default beans
		// (e.g. the default StaticMessageSource in a StaticApplicationContext).
		destroySingleton(beanName);

		// Remove any assumptions about by-type mappings.
		clearByTypeCache();

		// Reset all bean definitions that have the given bean as parent (recursively).
		for (String bdName : this.beanDefinitionNames) {
			if (!beanName.equals(bdName)) {
				BeanDefinition bd = this.beanDefinitionMap.get(bdName);
				if (beanName.equals(bd.getParentName())) {
					resetBeanDefinition(bdName);
				}
			}
		}
	}

总结上面步骤:

1, AbstractBeanDefinition的methodOverrides校验

2,对已经注册的beanName的处理

3,加入map 缓存

4,刷新缓存

4.2 alias别名注册

和上面beanName差不多,参照上面

5,通知监听器

最后,这里通知监听器,其实spring没有做什么,这里实现只为拓展,方便开发人员需要对注册的BeanDefinition事件进行监听时,可以通过注册监听器的方式将处理逻辑写入监听器

 

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部