美文网首页
Spring IOC容器一 容器初始化

Spring IOC容器一 容器初始化

作者: hopelty | 来源:发表于2019-10-09 19:03 被阅读0次
  1. 由于ContextLoaderListener类实现了ServletContextListener接口,tomcat容器启动完成后,会触发调用ContextLoaderListener的contextInitialized()。
    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }

然后进入initWebApplicationContext()。

if (this.context instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
        if (!cwac.isActive()) {
                // The context has not yet been refreshed -> provide services such as
                // setting the parent context, setting the application context id, etc
                if (cwac.getParent() == null) {
                    // The context instance was injected without an explicit parent ->
                    // determine parent for root web application context, if any.
                    ApplicationContext parent = loadParentContext(servletContext);
                    cwac.setParent(parent);
                }
                configureAndRefreshWebApplicationContext(cwac, servletContext);
        }
}

我们主要关注的是configureAndRefreshWebApplicationContext(cwac, servletContext),代码如下:

    protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
        if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
            // The application context id is still set to its original default value
            // -> assign a more useful id based on available information
            String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
            if (idParam != null) {
                wac.setId(idParam);
            }
            else {
                // Generate default id...
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }

        wac.setServletContext(sc);
        String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
        if (configLocationParam != null) {
            wac.setConfigLocation(configLocationParam);
        }

        // The wac environment's #initPropertySources will be called in any case when the context
        // is refreshed; do it eagerly here to ensure servlet property sources are in place for
        // use in any post-processing or initialization that occurs below prior to #refresh
        ConfigurableEnvironment env = wac.getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {
            ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
        }

        customizeContext(sc, wac);
        wac.refresh();
    }

关键方法是最后一行wac.refresh()。
同样地,main()中的SpringApplication.run()方法也会同样地调用到refresh(),来启动IOC容器,但他们生成的子对象不同,run()方法并不会调用loadBeanDefinition()方法,这也是spring初始化ioc容器的核心方法,定位、加载并注册了配置文件或注解修饰的所有bean。


下面我们具体来看下refresh()中的代码。

@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Propagate exception to caller.
                throw ex;
            }

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

prepareRefresh()顾名思义,主要是为刷新上下文做准备工作,如:设置启动时间、将active属性设置为true、将closed属性设置为false、检查声明的属性值(@Value、@PropertySources)是否在配置文件中是否全部配置等。其中,active和closed均为atomicBoolean类型。

创建 Bean 容器,加载并注册 Bean

接下来就是最核心的obtainFreshBeanFactory()方法:主要用来解析配置文件,并且将文件中的bean解析成BeanDefinition,以及完成 bean
的注册(bean的实例化不在该方法中)。
ObtainFreshBeanFactory()源码如下:

/**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        return getBeanFactory();
    }

点进refreshBeanFactory()继续看。值得一提的是,代码都被synchronnized关键字修饰,startupShutdownMonitor是new出来的object对象作为锁,这是常见的并发编程的代码方式。

/**
     * This implementation performs an actual refresh of this context's underlying
     * bean factory, shutting down the previous bean factory (if any) and
     * initializing a fresh bean factory for the next phase of the context's lifecycle.
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            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. 如果当前DefaultListableBeanFactory对象已经被创建了,则先销毁所有的beans,再把beanFactory销毁(beanFactory=null,赋值为null)。

2、新创建一个DefaultListableBeanFactory 的实例BeanFactory,设置唯一的标识,进行一些偏好化的设置。

3、关键的loadBeanDefinitions()的方法具体实现是在子类AbstractXmlApplicationContext和子类AnnotationConfigWebApplicationContext中的loadBeanDefinitions(),两个子类对应不同的配置方式:

姓名 技能
基于xml的配置 XmlBeanDefinitionReader
基于java注解的配置 AnnotatedBeanDefinitionReader

spring boot使用的注解方式配置bean是调用AnnotatedBeanDefinitionReader子类,而spring旧版本则是通过xml文件来配置bean的,两个类加载bean definition的思路相仿,其目的都是要把配置的bean通过BeanDefinitionReader.register()方法转化为bean definition,下面我们分别看看两个子类是如何加载bean definition的。

  • 首先来看XmlBeanDefinitionReader如何加载xml文件中的bean

XmlBeanDefinitionReader

    /**
     * Loads the bean definitions via an XmlBeanDefinitionReader.
     * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        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);
        loadBeanDefinitions(beanDefinitionReader);
    }

首先创建一个bean definition reader对象(xml方式则创建XmlBeanDefinitionReader、注解方式则创建AnnotatedBeanDefinitionReader),进入loadBeanDefinitions()方法。

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            reader.loadBeanDefinitions(configLocations);
        }
    }

从这个方法中,加载配置文件工作正式移交给XmlBeanDefinitionReader。如果Resources不为空,则进入重载方法loadBeanDefinitions(Resource[]),如果配置文件的字符串路径不为空,则进入重载方法loadBeanDefinitions(String[])中。

进入AbstractBeanDefinitionReader类处理Resource[],或者String[](分别将String路径读取,解析成Resource[]),然后分别单独解析每个Resource资源,调用子类XmlBeanDefinitionReader的loadBeanDefinitions()方法,在loadBeanDefinitions这个类中,loadBeanDefinitions方法有四个重载的方法:

  • public int loadBeanDefinitions(String location)
  • public int loadBeanDefinitions(Resource... resources)
  • public int loadBeanDefinitions(String location, Set<Resource> actualResources)
  • public int loadBeanDefinitions(String... locations)
    顺着调用路径往下走,我们进入public int loadBeanDefinitions(Resource... resources)看以下。
    /**
     * Load bean definitions from the specified XML file.
     * @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.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();
            }
        }
    }

获取EncodedResource对象的输入流,继续调用doLoadBeanDefinitions()方法。从下面的代码中看到,该方法将输入流转化成了Document文件对象,继续调用registerBeanDefinitions()方法。

    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {
        try {
            Document doc = doLoadDocument(inputSource, resource);
            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);
        }
    }

在registerBeanDefinitions()方法中,虽说名字上带有register。但并没有进入实际的解析和注册过程。而是创建一个DefaultBeanDefinitionDocumentReader(实现了接口BeanDefinitionDocumentReader )的实例,把解析和注册工作又委托给了BeanDefinitionDocumentReader,这里我们可以看到Spring的代码分工非常明确,前面load bean definition的工作交由XmlBeanDefinitionReader来完成,而这里register bean definition的工作则交由BeanDefinitionDocumentReader来完成。registerBeanDefinitions函数返回值为加载bean的数量。如下代码所示:

    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
        BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
        int countBefore = getRegistry().getBeanDefinitionCount();
        documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
        return getRegistry().getBeanDefinitionCount() - countBefore;
    }
    /**
     * This implementation parses bean definitions according to the "spring-beans" XSD
     * (or DTD, historically).
     * <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;
        logger.debug("Loading bean definitions");
        Element root = doc.getDocumentElement();
        doRegisterBeanDefinitions(root);
    }

可以看出,在DefaultBeanDefinitionDocumentReader中将Document对象解析成Element然后调用实际注册的doRegisterBeanDefinitions(从名字上也可以看出,doXXX方法完成实际的解析注册工作,例如doLoadBeanDefinitions、doGetBean、doRegister等)。

继续往下走,进入doRegisterBeanDefinitions()。

    /**
     * Register each bean definition within the given root {@code <beans/>} element.
     */
    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);
                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;
                }
            }
        }

        preProcessXml(root);
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);

        this.delegate = parent;
    }

这里的preProcessXml(root)和postProcessXml(root)默认为空方法,主要逻辑是在parseBeanDefinitions(root, this.delegate)中,继续往下走。

    /**
     * Parse the elements at the root level in the document:
     * "import", "alias", "bean".
     * @param root the DOM root element of the document
     */
    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);
        }
    }

方法最开始会先判断当前的delegate的命名空间是否为default,下面就是一个bean的xml文件,它的命名空间就是default的:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-autowire="byName">

从代码中可以看到,所有的配置都会进入两个分支: parseDefaultElement(ele, delegate); 和 delegate.parseCustomElement(ele);

<beans />、<alias />、<import />、<bean />标签的配置都会进入parseDefaultElement(ele, delegate)分支,而我们见过的<mvc />、<task />、<context />、<aop />等则会进入delegate.parseCustomElement(ele)分支。下面我们主要看一下parseDefaultElement(ele, delegate)分支。

    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)) { //如果碰到的是嵌套的 <beans /> 标签,需要递归
            // recurse
            doRegisterBeanDefinitions(ele);
        }
    }

如代码注释,我们是解析bean的情况(beans情况会递归调用doRegisterBeanDefinitions(ele)方法,最终还是会进入bean标签的情况),所以进入processBeanDefinition(ele, delegate)方法继续看。

    /**
     * Process the given bean element, parsing the bean definition
     * and registering it with the registry.
     */
    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // 将 <bean /> 节点中的信息提取出来,然后封装到一个BeanDefinitionHolder中
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            // 如果有自定义,则进行相应的解析
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                // Register the final decorated instance.
                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));
        }
    }

我们先跟进BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele)这一行代码,后面的代码稍后看。

    /**
     * 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}.
     */
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
   // 将 name 属性的定义按照 ”逗号、分号、空格“ 切分,形成一个别名列表数组,
   // 当然,如果你不定义的话,就是空的了
        String id = ele.getAttribute(ID_ATTRIBUTE);
        String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

        List<String> aliases = new ArrayList<String>();
        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.isDebugEnabled()) {
                logger.debug("No XML 'id' specified - using '" + beanName +
                        "' as bean name and " + aliases + " as aliases");
            }
        }

        if (containingBean == null) {
            checkNameUniqueness(beanName, aliases, ele);
        }
// 根据 <bean ...>...</bean> 中的配置创建 BeanDefinition,然后把配置中各标签的信息都设置到实例中
        AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
        //当没有设置id、name时,beanName为空,为beanName赋值,以传入BeanDefinitionHolder中
        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.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);
            return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
        }

        return null;
    }

我们回到解析bean definition的入口方法processBeanDefinition(Element ele, BeanDefinitionParserDelegate)。

    /**
     * Process the given bean element, parsing the bean definition
     * and registering it with the registry.
     */
    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        // 将 <bean /> 节点转换为 BeanDefinitionHolder
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            // 如果有自定义属性的话,进行相应的解析
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                // Register the final decorated instance.
                //注册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));
        }
    }

我们上面根据bean的配置信息创建了一个BeanDefinitionHolder实例,这个实例包括了beanDefinition信息、beanName和aliases(别名),接下来我们看看是如何注册bean的。

    /**
     * Register the given bean definition with the given bean factory.
     * @param definitionHolder the bean definition including name and aliases
     * @param registry the bean factory to register with
     * @throws BeanDefinitionStoreException if registration failed
     */
    public static void registerBeanDefinition(
            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
            throws BeanDefinitionStoreException {

        // Register bean definition under primary name.
        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 alias : aliases) {
                registry.registerAlias(beanName, alias);
            }
        }
    }

注册

根据上面的代码我们可以看到,注册bean的主要逻辑在registry.registerBeanDefinition()方法,注册bean后,会把所有别名全部注册(如果有别名的话),实际就是把alias作为key,beanName作为value,存储在一个map中。根据alias查询bean时,会把alias转换为beanName,再进行bean查询。这段代码逻辑比较简单,我们主要还是把关注点放在registerBeanDefinition()方法中。

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

        if (beanDefinition instanceof AbstractBeanDefinition) {
            try {
                ((AbstractBeanDefinition) beanDefinition).validate();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Validation of bean definition failed", ex);
            }
        }
        //考虑bean覆盖情况
        BeanDefinition oldBeanDefinition;
        //所有bean definition均会保存在bean definition map中
        oldBeanDefinition = this.beanDefinitionMap.get(beanName);
        // 处理重复名称的 Bean 定义的情况
        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()) {
                // log...用框架定义的 Bean 覆盖用户自定义的 Bean 
                // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
                if (this.logger.isWarnEnabled()) {
                // log...用新的 Bean 覆盖旧的 Bean
                    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 {
            // 判断是否已经有其他的 Bean 开始初始化了.
            // 注意,"注册Bean" 这个动作结束,Bean 还没有初始化
            // 在 Spring 容器启动的最后,会 预初始化 所有的 singleton beans
            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<String>(this.beanDefinitionNames.size() + 1);
                    updatedDefinitions.addAll(this.beanDefinitionNames);
                    updatedDefinitions.add(beanName);
                    this.beanDefinitionNames = updatedDefinitions;
                    if (this.manualSingletonNames.contains(beanName)) {
                        Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames);
                        updatedSingletons.remove(beanName);
                        this.manualSingletonNames = updatedSingletons;
                    }
                }
            }
            else {
                // 最正常的应该是进到这里。
                // Still in startup registration phase
                // 将 BeanDefinition 放到这个 map 中,这个 map 保存了所有的 BeanDefinition
                this.beanDefinitionMap.put(beanName, beanDefinition);
                // 这是个 ArrayList,所以会按照 bean 配置的顺序保存每一个注册的 Bean 的名字 
                this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
            }
            this.frozenBeanDefinitionNames = null;
        }

        if (oldBeanDefinition != null || containsSingleton(beanName)) {
            resetBeanDefinition(beanName);
        }
    }

总结一下:

  • XmlBeanDefinitionReader负责统计bean的注册个数和解析xml文档
  • BeanDefinitionDocumentReader负责依据xml文档解析和注册bean
  • BeanDefinitionParseDelegate负责实际的解析工作

以上我们一起过了一遍XmlBeanDefinitionReader解析xml文件的方式注册bean,下面我们一起看一下AnnotatedBeanDefinitionReader是如何解析bean配置并注册bean的。

AnnotationConfigWebApplicationContext

AnnotationConfigWebApplicationContext继承自AbstractRefreshableWebApplicationContext,接受注解的类作为输入(特殊的@Configuration注解类,一般的@Component、@Repository、@Service、@Controller等注解类)。允许一个一个的注入,同样也能使用类路径扫描。对于web环境,基本上是和AnnotationConfigApplicationContext等价的。使用AnnotatedBeanDefinitionReader来对注解的bean进行处理,使用ClassPathBeanDefinitionScanner来对类路径下的bean进行扫描。

进入AnnotationConfigWebApplicationContext.loadBeanDefinitions()方法。

    /**
     * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
     * any classes specified by {@link #register(Class...)} and scan any packages
     * specified by {@link #scan(String...)}.
     * <p>For any values specified by {@link #setConfigLocation(String)} or
     * {@link #setConfigLocations(String[])}, attempt first to load each location as a
     * class, registering a {@code BeanDefinition} if class loading is successful,
     * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
     * assume the value is a package and attempt to scan it for annotated classes.
     * <p>Enables the default set of annotation configuration post processors, such that
     * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
     * <p>Configuration class bean definitions are registered with generated bean
     * definition names unless the {@code value} attribute is provided to the stereotype
     * annotation.
     * @param beanFactory the bean factory to load bean definitions into
     * @see #register(Class...)
     * @see #scan(String...)
     * @see #setConfigLocation(String)
     * @see #setConfigLocations(String[])
     * @see AnnotatedBeanDefinitionReader
     * @see ClassPathBeanDefinitionScanner
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
        AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
        ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);

        BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
        //若BeanNameGenerator不为空,则AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionReader使用设置的BeanNameGenerator;若为空,则取各自默认BeanNameGenerator
        if (beanNameGenerator != null) {
            reader.setBeanNameGenerator(beanNameGenerator);
            scanner.setBeanNameGenerator(beanNameGenerator);
            beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
        }

        ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
        //同理,ScopeMetadataResolver与BeanNameGenerator相同逻辑;ScopeMetadataResolver用于解析@Scope注解(SingleTon、Prototype等)
        if (scopeMetadataResolver != null) {
            reader.setScopeMetadataResolver(scopeMetadataResolver);
            scanner.setScopeMetadataResolver(scopeMetadataResolver);
        }

        if (!this.annotatedClasses.isEmpty()) {
            //配置注解修饰的bean
            if (logger.isInfoEnabled()) {
                logger.info("Registering annotated classes: [" +
                        StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
            }
            reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
        }

        if (!this.basePackages.isEmpty()) {
            if (logger.isInfoEnabled()) {
                logger.info("Scanning base packages: [" +
                        StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
            }
            //扫描包路径下,所有的@Configuration, @Repository, @Controller, @Service等注解修饰的类
            scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
        }

        //获取配置位置,先当作annotatedClass来处理,如果抛异常,则当作包路径来处理
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String configLocation : configLocations) {
                try {
                    Class<?> clazz = getClassLoader().loadClass(configLocation);
                    if (logger.isInfoEnabled()) {
                        logger.info("Successfully resolved class for [" + configLocation + "]");
                    }
                    reader.register(clazz);
                }
                catch (ClassNotFoundException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not load class for config location [" + configLocation +
                                "] - trying package scan. " + ex);
                    }
                    int count = scanner.scan(configLocation);
                    if (logger.isInfoEnabled()) {
                        if (count == 0) {
                            logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
                        }
                        else {
                            logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
                        }
                    }
                }
            }
        }
    }

代码首先判断BeanNameGenerator是否为空,如果不为空,则把此对象赋值给AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner两个类,如果为空,则使用默认的BeanNameGenerator。ScopeMetadataResolver同理。

往下走,如果发现有被@Configuration, @Controller, @Service, @Component等注解修饰的类,就调用AnnotatedBeanDefinitionReader.register()方法来注册bean definition,该方法我们后面细看,先往下走。

判断如果包路径不为空,则读取包路径,对路径下的所有被@Configuration等注解修饰的类进行加载bean definition。

最后,获取配置文件,先当作annotatedClass来处理,如果不是annotatedClass(抛异常),则当作包路径来处理。

下面我们来看一下reader和scanner是如何加载bean definition的。
register(Class<?>… annotatedClasses):

public void register(Class<?>... annotatedClasses) {
    Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
    this.reader.register(annotatedClasses);
}

scan(String… bashPackages):

public void scan(String... basePackages) {
    Assert.notEmpty(basePackages, "At least one base package must be specified");
    this.scanner.scan(basePackages);
}

可以看到上面两个方法分别调用了AnnotatedBeanDefinitionReader的register()和ClassPathBeanDefinitionScanner的scan()方法。实际上,二者的目标是一致的,都是去找到Spring注解标记的类,来生成并注册bean definition到容器内。不同的是,AnnotatedBeanDefinitionReader的register是指定要注册bean的类,而ClassPathBeanDefinitionScanner的scan则会自动扫描给定包路径下的所有的类,依次处理被注解标记的类。最终生成AnnotatedBeanDefinitionReader,和前面的DefaultBeanDefinitionDocumentReader注册bean definition相同,生成一个BeanDefinitionHolder对象,调用registerBeanDefinition()方法。

到这里我们就初始化了ioc容器,<bean />或被@Configuration等注解修饰的类已经转化成了bean definition,并且把所有bean definition逐一注册。下一节我们需要回到refresh()方法,继续看后面的代码。

相关文章

  • Spring IoC一、容器初始化过程

    Spring IoC一、容器初始化过程 本文追踪Spring运行程序流程分析Ioc容器初始化的过程。依赖注入的部分...

  • Spring - IOC容器初始化

    最近阅读了一些Spring Framework里IOC容器的初始化相关的代码。 IOC容器的初始化,将对象交给容器...

  • spring-core

    bean: 应用里被Spring IoC容器管理的对象叫做bean.Spring IoC容器负责bean的初始化,...

  • Spring中IOC容器的初始化过程

    Spring IOC容器初始化过程分为Resource定位,载入解析,注册。IOC容器初始化过程中不包含Bean的...

  • 2.Spring IoC 容器

    1.Spring IoC 容器 IoC 容器 Spring 容器是 Spring 框架的核心。容器将创建对象,把它...

  • Spring IoC - 依赖注入 源码解析

    前言 上一篇文章中,我们介绍了Spring IoC 的容器初始化过程 - IoC 容器初始化 本篇文章中,我们继续...

  • Spring核心:IOC容器的实现(四)

    IOC容器的初始化过程: Spring的IoC容器初始化包括:Bean定义资源文件的定位、载入和注册3个基本过程。...

  • 2.IOC原理分析

    要想使用Spring IOC,必须要创建Spring IOC容器 ? 什么是IOC容器? 所谓的IoC容器就是指的...

  • spring-core-1.1~1.9 IoC容器

    1. IoC容器 本章介绍Spring的控制反转,即IoC容器. 1.1 Spring IoC容器和bean简介 ...

  • 一、Spring核心篇

    第2章Spring Framework的核心:IoC容器的实现 2.1Spring IoC容器概述 1.IOC容器...

网友评论

      本文标题:Spring IOC容器一 容器初始化

      本文链接:https://www.haomeiwen.com/subject/wowlpctx.html