Spring IoC:refresh的obtainFreshBe

2020-08-31  本文已影响0人  今年五年级

一 简介

本方法会解析所有的spring配置文件,如spring-redis.xml,将所有spring配置文件中的bean定义封装成BeanDefinition然后加载到BeanFactory中。加载到beanFactory中主要是指:

  1. beanDefinitionNames缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 集合
  2. beanDefinitionMap缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 和 BeanDefinition 映射
  3. aliasMap缓存:所有被加载到 BeanFactory 中的 bean 的 beanName 和别名映射

二 源码

AbstractApplicationContext 类的方法,obtain:获得
这里使用了委派设计模式,父类定义了抽象的 refreshBeanFactory()方法,具体实现调用子类容器的 refreshBeanFactory()方法

    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        return getBeanFactory();
    }
    /**
     * 子类必须实现此方法才能执行实际的配置负载
     * The method is invoked by {@link #refresh()} before any other initialization work.
     * <p>A subclass will either create a new bean factory and hold a reference to it,
     * or return a single BeanFactory instance that it holds. In the latter case, it will
     * usually throw an IllegalStateException if refreshing the context more than once.
     * @throws BeansException if initialization of the bean factory failed
     * @throws IllegalStateException if already initialized and multiple refresh
     * attempts are not supported
     */
    protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;

2.1

AbstractApplicationContext 类中只抽象定义了 refreshBeanFactory()方法,容器真正调用的是其子类 AbstractRefreshableApplicationContext 实现的 refreshBeanFactory()方法,方法的源码如下

    @Override
    protected final void refreshBeanFactory() throws BeansException {
        // 如果已经有了容器,则销毁容器中的bean并关闭容器
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            // 初始化一个 DefaultListableBeanFactory作为IOC容器
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            // 定制化ioc容器,设置启动参数,开启注解自动装配
            customizeBeanFactory(beanFactory);
            // 使用委派模式,在当前类中只定义了抽象的 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);
        }
    }

    /**
     * 将bean定义加载到给定的bean工厂中, 通常是通过委托给一个或多个bean定义读取器.
     */
    protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
            throws BeansException, IOException;

2.2

AbstractRefreshableApplicationContext 中只定义了抽象的 loadBeanDefinitions 方法,容器真正调用的是其子类 AbstractXmlApplicationContext 对 该 方 法 的 实 现 ,
AbstractXmlApplicationContext 的主要源码如下:

    /**
     * 通过XmlBeanDefinitionReader加载bean定义
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // 创建一个xmlBeanDefinitionReader(bean定义信息读取器)
        // 然后通过回调设置给传入的容器中取,容器使用该读取器读取bean定义资源
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        // 为bean定义信息读取器设置spring资源加载器,之所以用this,是因为本类的祖先类AbstractApplicationContext 继承 DefaultResourceLoader
        // 因此本类自身就是一个资源加载器
        beanDefinitionReader.setResourceLoader(this);
        // 为bean定义信息读取器设置 SAX xml解析器
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // 当bean定义信息读取器读取bean定义的xml资源文件时,采用xml的校验机制
        initBeanDefinitionReader(beanDefinitionReader);
        // bean定义信息读取器真正加载
        loadBeanDefinitions(beanDefinitionReader);
    }
    private boolean validating = true;
    protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
        reader.setValidating(this.validating);
    }

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        // 这里返回的null,因此直接走下面的string[]分支
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }
        // classpath:application-message.xml
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            reader.loadBeanDefinitions(configLocations);
        }
    }

上面提到的resource接口是Spring中整合的获取资源的工具,此接口是Spring为了统一读取诸如本地文件、classpath项目路径下的文件、url互联网上的文件等不同类型渠道的资源,封装隐藏如打开流、关闭流、报错处理等大量重复模板代码,而专程设计提供的接口类。
相关文章:https://blog.csdn.net/u010086122/article/details/81607167

2.3

image.png

上面的reader.loadBeanDefinitions传入类似于classpath:application-message.xml这样的配置文件路径,然后代码位于 AbstractBeanDefinitionReader,方法源码如下

@Override
    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;
    }

    @Override
    public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
        return loadBeanDefinitions(location, null);
    }

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
        // 获取的是创建xmlBeanDefinitionReader时候配置的资源加载器,当时是AbstractXmlApplicationContext对象实例
        ResourceLoader resourceLoader = getResourceLoader();
        if (resourceLoader == null) {
            throw new BeanDefinitionStoreException(
                    "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
        }
        // 上面提到的这个资源加载器曾爷爷是AbstractApplicationContext,层级关系如上图
        if (resourceLoader instanceof ResourcePatternResolver) {
            // Resource pattern matching available.
            try {
                // 将classpath下的bean定义配置文件解析为spring ioc容器封装的资源
                // 加载多个指定位置的资源
                Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
                int count = loadBeanDefinitions(resources);
                if (actualResources != null) {
                    Collections.addAll(actualResources, resources);
                }
                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);
            }
            return count;
        }
    }

    @Override
    public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
        Assert.notNull(resources, "Resource array must not be null");
        int count = 0;
        for (Resource resource : resources) {
            count += loadBeanDefinitions(resource);
        }
        return count;
    }

2.4

loadBeanDefinitions(Resource resouce)方法位于AbstractBeanDefinitionReader的子类 XmlBeanDefinitionReader

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

    /**
     * 从指定的xml文件加载bean定义信息
     * @param encodedResource the resource descriptor for the XML file,
     * allowing to specify an encoding to use for parsing the file
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    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 的 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();
            }
        }
    }
/**
     * 真正的从指定的XML文件加载bean定义。
     * @param inputSource the SAX InputSource to read from
         要读取的SAX输入源
     * @param resource the resource descriptor for the XML file
         XML文件的资源描述符
     * @return the number of bean definitions found
         找到的bean定义的数量
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     * @see #doLoadDocument
     * @see #registerBeanDefinitions
     */
    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {

        try {
            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);
        }
    }

    protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
        return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
                getValidationModeForResource(resource), isNamespaceAware());
    }

关于EntityResolver
Document生成和解析XML

至此,Spring IOC 容器根据定位的 Bean 定义资源文件,将其加载读入并转换成为 Document 对象过程完成。但是这些 Document 对象并没有按照 Spring 的 Bean 规则进行解析

2.5

接下来要继续分析 Spring IOC 容器将载入的 Bean 定义资源文件转换为 Document 对象之后,是如何将其解析为 Spring IOC 管理的 Bean 对象并将其注册到容器中的.
这一步骤在XmlBeanDefinitionReader中进行

    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;
    }

2.6

按照 Spring 的 Bean 规则对 Document 对象解析的过程是在接口BeanDefinitionDocumentReader的实现类 DefaultBeanDefinitionDocumentReader 中实现的

    /**
     * 该实现通过 “spring-beans” XSD或者历史的DTD来解析Bean定义
     * <p>Opens a DOM Document; then initializes the default settings
     * specified at the {@code <beans/>} level; then parses the contained bean definitions.
     */
    @Override
    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
        this.readerContext = readerContext;
        doRegisterBeanDefinitions(doc.getDocumentElement());
    }

/**
     * 在给定的根元素{@code <beans/>}中注册每个bean定义
     */
    @SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
    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);
                // 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;
                }
            }
        }
        // 在解析 Bean 定义之前,进行自定义的解析,增强解析过程的可扩展性,留给子类实现
        preProcessXml(root);
        // 从 Document 的根元素开始解析,对于Spring的配置文件来说,理论上应该都是<beans>
        parseBeanDefinitions(root, this.delegate);
        // 在解析 Bean 定义之后,进行自定义的解析,增强解析过程的可扩展性,留给子类实现
        postProcessXml(root);

        this.delegate = parent;
    }

/**
     * 解析在document中的跟级别的元素: "import", "alias", "bean".
     * @param root the DOM root element of the document
     */
    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
        // Bean 定义的 Document 对象是否使用了 Spring 默认的 XML 命名空间
        if (delegate.isDefaultNamespace(root)) {
            // NodeList nl = root.getChildNodes();
            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;
                    // 如果节点的命名空间是 Spring 默认的命名空间
                    // 则走 parseDefaultElement(ele, delegate) 方法进行解析
                    // 例如最常见的:<bean>
                    if (delegate.isDefaultNamespace(ele)) {
                        parseDefaultElement(ele, delegate);
                    }
                    else {
                    // 如果节点的命名空间不是 Spring 默认的命名空间,也就是自定义命名空间
                    // 则走 delegate.parseCustomElement(ele) 方法进行解析
                    // 例如常见的: <context:component-scan/>、<aop:aspectj-autoproxy/>
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        }
        else {
            // Document 的根节点没有使用 Spring 默认的命名空间,则使用用户自定义的
            // 解析规则解析 Document 根节
            delegate.parseCustomElement(root);
        }
    }
    /**
     * Determine whether the given URI indicates the default namespace.
     */
    public boolean isDefaultNamespace(@Nullable String namespaceUri) {
        return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri));
    }
    public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans";
    public String getNamespaceURI(Node node) {
        return node.getNamespaceURI();
    }

    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)) {
            // recurse
            doRegisterBeanDefinitions(ele);
        }
    }

    /**
     *  处理给定的bean元素,解析bean定义
     * and registering it with the registry.
     */
    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        // BeanDefinitionHolder 是对 BeanDefinition 的封装,即 Bean 定义的封装类
        //对 Document 对象中<Bean>元素的解析由 BeanDefinitionParserDelegate 实现
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                //向 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);
            }
            // 在完成向 Spring IOC 容器注册解析得到的 Bean 定义之后,发送注册事件
            getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
        }
    }

默认的命名空间为:http://www.springframework.org/schema/beans,其他都是自定义命名空间,例如 aop 的命名空间为:http://www.springframework.org/schema/aop

通过上述Spring IOC容器对载入的Bean定义Document解析可以看出, 我们在Spring 配置文件中需要用到<import resource="">标签来引入其他配置文件,<import resource="classpath:XXXXX.xml">这代表的是引入的是/WIN-INF/classes/xxxxx.xml文件,项目只会到这个目录下去寻找文件,其实就是src/main/resources文件下面的xxxxx.xml文件。Spring IOC 容器在解析时会首先将指定导入的资源加载进容器中。
使用<ailas>别名时,Spring IOC 容器首先将别名元素所定义的别名注册到容器中。
对于既不是<import>元素, 又不是<alias>元素的元素, 即 Spring 配置文件中普通的<bean>元素的解析由 BeanDefinitionParserDelegate 类的 parseBeanDefinitionElement 方法来实现

2.7

BeanDefinitionParserDelegate 解析 Bean 定义资源文件中的<bean>元素:

@Nullable
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
        return parseBeanDefinitionElement(ele, null);
    }

    /**
     * Parses the supplied {@code <bean>} element. May return {@code null}
     * if there were errors during parse. Errors are reported to the
     * {@link org.springframework.beans.factory.parsing.ProblemReporter}.
     */
    @Nullable
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
        // 获取<Bean>元素中的 id 属性值
        String id = ele.getAttribute(ID_ATTRIBUTE);
        // 获取<Bean>元素中的 name 属性值,实际上是别名,可以多个
        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));
        }
        // 如果<Bean>元素中没有配置 id 属性时,将别名中的第一个值赋值给 beanName
        String beanName = id;
        if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
            beanName = aliases.remove(0);
        }
        // 检查<Bean>元素所配置的 id 或者 name 的唯一性,containingBean 标识<Bean>
        // 元素中是否包含子<Bean>元素
        if (containingBean == null) {
        // 检查<Bean>元素所配置的 id、name 或者别名是否重复
            checkNameUniqueness(beanName, aliases, ele);
        }
        // 详细对<Bean>元素中配置的 Bean 定义进行解析的地方
        AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
        if (beanDefinition != null) {
            if (!StringUtils.hasText(beanName)) {
                try {
                    if (containingBean != null) {
//如果<Bean>元素中没有配置 id、别名或者 name,且没有包含子元素
//<Bean>元素,为解析的 Bean 生成一个唯一 beanName 并注册
                        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);
                        }
                    }
                }
                catch (Exception ex) {
                    error(ex.getMessage(), ele);
                    return null;
                }
            }
            String[] aliasesArray = StringUtils.toStringArray(aliases);
            return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
        }

        return null;
    }

    /**
     * Validate that the specified bean name and aliases have not been used already
     * within the current level of beans element nesting.
     */
    protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
        String foundName = null;

        if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
            foundName = beanName;
        }
        if (foundName == null) {
            foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
        }
        if (foundName != null) {
            error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
        }

        this.usedNames.add(beanName);
        this.usedNames.addAll(aliases);
    }

Spring配置中<bean>的id和name属性

上一篇下一篇

猜你喜欢

热点阅读