码迷,mamicode.com
首页 > 编程语言 > 详细

Spring容器的初始化流程

时间:2019-01-24 23:05:23      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:lan   mod   object c   pos   解决   查看   tee   epo   raw   

一、创建BeanFactory流程

1、流程入口

创建BeanFactory的流程是从refresh方法的第二步开始的,通过调用obtainFreshBeanFactory方法完成流程。

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

2、流程分析

创建BeanFactory的流程是从第二步开始的,调用AbstractApplicationContext类中的obtainFreshBeanFactory方法:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		// 主要是通过该方法完成IoC容器的刷新
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
}

调用AbstractRefreshableApplicationContext中的refreshBeanFactory方法:

protected final void refreshBeanFactory() throws BeansException {
    // 如果之前有IoC容器,则销毁
    if (hasBeanFactory()) {
        destroyBeans();
        closeBeanFactory();
    }
    try {
        // 创建IoC容器,也就是DefaultListableBeanFactory
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        beanFactory.setSerializationId(getId());
        // 设置工厂的属性:是否允许BeanDefinition覆盖和是否允许循环依赖
        customizeBeanFactory(beanFactory);
        // 调用载入BeanDefinition的方法,在当前类中只定义了抽象的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);
    }
}

其中调用createBeanFactory方法创建IoC容器。这里创建的是DefaultListableBeanFactory,它是真正用于管理Bean实例及BeanDefeation的工厂。

二、加载BeanDefeation流程

1、流程入口

此流程是从AbstractRefreshableApplicationContext的refreshBeanFactory方法开始的,代码如上所示,通过loadBeanDefinitions(beanFactory)进行BeanDefeation的加载。

 loadBeanDefinitions(beanFactory);

2、流程图

这里的调用较为复杂,可通过下面流程图进行说明:

sequenceDiagram AbstractRefreshableApplicationContext->>AbstractXmlApplicationContext:loadBeanDefinitions(DefaultListableBeanFactory) AbstractXmlApplicationContext->>AbstractXmlApplicationContext:loadBeanDefinitions(XmlBeanDefinitionReader) AbstractXmlApplicationContext->>XmlBeanDefinitionReader:loadBeanDefinitions(Resource) XmlBeanDefinitionReader->>XmlBeanDefinitionReader:loadBeanDefinitions(EncodedResource) XmlBeanDefinitionReader->>XmlBeanDefinitionReader:doLoadBeanDefinitions() XmlBeanDefinitionReader->>XmlBeanDefinitionReader:registerBeanDefinitions()

3、流程分析

在创建完Ioc容器之后,调用AbstractXmlApplicationContext的loadBeanDefinitions进行beanDefeation的加载,其代码如下:

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // 创建一个BeanDefinition阅读器,通过阅读XML文件,真正完成BeanDefinition的加载和注册
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    beanDefinitionReader.setEnvironment(this.getEnvironment());
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

    initBeanDefinitionReader(beanDefinitionReader);
    // 委托给BeanDefinition阅读器去加载BeanDefinition
    loadBeanDefinitions(beanDefinitionReader);
}

再调用其重载方法loadBeanDefinitions,代码如下:

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    // 获取资源的定位
    // 这里getConfigResources是一个空实现,真正实现是调用子类的获取资源定位的方法
    // 比如:ClassPathXmlApplicationContext中进行了实现,而FileSystemXmlApplicationContext没有使用该方法
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
        // XML Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的资源
        reader.loadBeanDefinitions(configResources);
    }
    // 如果子类中获取的资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        // XML Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的资源
        reader.loadBeanDefinitions(configLocations);
    }
}

再调用的方法,代码如下:

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

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isInfoEnabled()) {
        logger.info("Loading XML bean definitions from " + encodedResource.getResource());
    }

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

具体的读取过程在doLoadBeanDefinitions方法中进行,将读取的beanDefinition信息进行注册:

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
    throws BeanDefinitionStoreException {
    try {
        // 通过DOM4J加载解析XML文件,最终形成Document对象
        Document doc = doLoadDocument(inputSource, resource);
        // 通过对Document对象的操作,完成BeanDefinition的加载和注册工作
        return registerBeanDefinitions(doc, resource);
    }
    //抛出异常。。。
}

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    // 创建BeanDefinitionDocumentReader来解析Document对象,完成BeanDefinition解析
    BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    // 获得容器中已经注册的BeanDefinition数量
    int countBefore = getRegistry().getBeanDefinitionCount();
    //解析过程入口,BeanDefinitionDocumentReader只是个接口,具体的实现过程在DefaultBeanDefinitionDocumentReader完成
    documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    // 统计新的的BeanDefinition数量
    return getRegistry().getBeanDefinitionCount() - countBefore;
}

在上面的registerBeanDefinitions方法中,关注两个方法:

  • createReaderContext(),主要用于获取NameSpaceResolver

  • registerBeanDefinitions(),通过获取的获取NameSpaceResolver查找对应的NameSpaceHandler,解析文档,得到BeanDefinition,并进行注册。

    :这里是通过/src/main/resources/META-INF/spring.handlers文件进行匹配的

首先查看createReaderContext方法:

public XmlReaderContext createReaderContext(Resource resource) {
    return new XmlReaderContext(resource, this.problemReporter, this.eventListener, this.sourceExtractor, this, getNamespaceHandlerResolver());
}

public NamespaceHandlerResolver getNamespaceHandlerResolver() {
    if (this.namespaceHandlerResolver == null) {
        this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver();
    }
    return this.namespaceHandlerResolver;
}

protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
    ClassLoader cl = (getResourceLoader() != null ? getResourceLoader().getClassLoader() : getBeanClassLoader());
    return new DefaultNamespaceHandlerResolver(cl);
}

通过这三个方法,将NamespaceHandlerResolver初始化成功。

再查看DefaultBeanDefinitionDocumentReader的registerBeanDefinitions方法,代码如下:

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    this.readerContext = readerContext;
    logger.debug("Loading bean definitions");
    // 获得Document的根元素<beans>标签
    Element root = doc.getDocumentElement();
    // 真正实现BeanDefinition解析和注册工作
    doRegisterBeanDefinitions(root);
}

这里的doRegisterBeanDefinitions是真正进行BeanDefinition解析和注册工作的。

protected void doRegisterBeanDefinitions(Element root) {
    // 这里使用了委托模式,将具体的BeanDefinition解析工作交给了BeanDefinitionParserDelegate去完成
    BeanDefinitionParserDelegate parent = this.delegate;
    this.delegate = createDelegate(getReaderContext(), root, parent);

    // 判断该根标签是否包含http://www.springframework.org/schema/beans默认命名空间
    if (this.delegate.isDefaultNamespace(root)) {
        String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
        if (StringUtils.hasText(profileSpec)) {
            String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
                profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                                "] not matching: " + getReaderContext().getResource());
                }
                return;
            }
        }
    }
    // 在解析Bean定义之前,进行自定义的解析,增强解析过程的可扩展性
    preProcessXml(root);
    // 委托给BeanDefinitionParserDelegate,从Document的根元素开始进行BeanDefinition的解析
    parseBeanDefinitions(root, this.delegate);
    // 在解析Bean定义之后,进行自定义的解析,增加解析过程的可扩展性
    postProcessXml(root);

    this.delegate = parent;
}

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    // 加载的Document对象是否使用了Spring默认的XML命名空间(beans命名空间)
    if (delegate.isDefaultNamespace(root)) {
        // 获取Document对象根元素的所有子节点(bean标签、import标签、alias标签和其他自定义标签context、aop等)
        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;
                // bean标签、import标签、alias标签,则使用默认解析规则
                if (delegate.isDefaultNamespace(ele)) {
                    parseDefaultElement(ele, delegate);
                }
                else {//像context标签、aop标签、tx标签,则使用用户自定义的解析规则解析元素节点
                    delegate.parseCustomElement(ele);
                }
            }
        }
    }
    else {
        // 如果不是默认的命名空间,则使用用户自定义的解析规则解析元素节点
        delegate.parseCustomElement(root);
    }
}

这里根据是否默认的命名空间和标签进行不同的处理,我们先关注默认的处理。

如下,在parseDefaultElement中进行默认标签的解析:

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>标签
    else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
        processBeanDefinition(ele, delegate);
    }
    // 解析内置<bean>标签
    else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
        // 递归调用
        doRegisterBeanDefinitions(ele);
    }
}

这里重点关注一下bean标签的解析,如上,调用processBeanDefinition方法。

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // 解析<bean>标签,获取BeanDefinition
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        // 如果需要,则装饰BeanDefinition对象
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // Register the final decorated instance.
            // 注册最终的BeanDefinition到BeanDefinitionRegistry(DefaultListableBeanFactory)
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
        }
        catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to register bean definition with name ‘" +
                                     bdHolder.getBeanName() + "‘", ele, ex);
        }
        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
}

这里通过对bean的解析获取BeanDefinition对象,并对其进行装饰,最终将BeanDefinition注册到DefaultListableBeanFactory中,通过Map集合的方式进行存储。

这里调用BeanDefinitionParserDelegate中的三个重载方法parseBeanDefinitionElement方法进行bean标签的解析,代码如下:

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
    // 解析<bean>标签,获取BeanDefinition对象
    return parseBeanDefinitionElement(ele, null);
}

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

    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) {
        // 检查bean的id或者name是否唯一
        checkNameUniqueness(beanName, aliases, ele);
    }
    // 解析<bean>标签,获取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);
                    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);
        // 将BeanDefinition对象和BeanName封装到BeanDefinitionHolder对象中
        return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
    }

    return null;
}

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

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

    String className = null;
    // 获取bean标签的class属性
    if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
        className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
    }
    String parent = null;
    // 获取bean标签的parent属性
    if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
        parent = ele.getAttribute(PARENT_ATTRIBUTE);
    }

    try {
        // 创建BeanDefinition对象GenericBeanDefinition
        AbstractBeanDefinition bd = createBeanDefinition(className, parent);
        // 解析<bean>标签的属性
        parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
        /** 解析<bean>标签的子标签  --- begin**/
        // 解析<description>标签
        bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
        // 解析<meta>标签
        parseMetaElements(ele, bd);
        // 解析<lookup-method>标签
        parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
        // 解析<replaced-method>标签
        parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

        // 解析<constructor-arg>标签
        parseConstructorArgElements(ele, bd);
        // 解析<property>标签
        parsePropertyElements(ele, bd);
        // 解析<qualifier>标签
        parseQualifierElements(ele, bd);
        /** 解析<bean>标签的子标签  --- end**/
        bd.setResource(this.readerContext.getResource());
        bd.setSource(extractSource(ele));
        return bd;
    }
   //抛出异常。。。
    return null;
}

三、创建Bean流程

1、流程入口

创建Bean的流程是refresh方法中的第11步:

// 实例化剩余的单例bean(非懒加载方式)
// 注意事项:Bean的IoC、DI和AOP都是发生在此步骤
finishBeanFactoryInitialization(beanFactory);

2、流程图

sequenceDiagram AbstractApplicationContext->>DefaultListableBeanFactory:preInstantiateSingletons DefaultListableBeanFactory->>AbstractBeanFactory:getBean AbstractBeanFactory->>AbstractBeanFactory:doGetBean AbstractBeanFactory->>AbstractAutowireCapableBeanFactory:createBean AbstractAutowireCapableBeanFactory->>AbstractAutowireCapableBeanFactory:doCreateBean

3、流程分析

首先通过finishBeanFactoryInitialization方法,进入DefaultListableBeanFactory的preInstantiateSingletons方法中,代码如下:

public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }

    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // 触发所有非懒加载方式的单例bean的创建
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 如果bean不是抽象的,而且是单例的,同时还不是懒加载的,则进行下面的操作
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 如果bean是一个工厂bean,则走下面的方法
            if (isFactoryBean(beanName)) {
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    final FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                                                    ((SmartFactoryBean<?>) factory)::isEagerInit,
                                                                    getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                       ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            else { // 普通bean走下面的方法
                getBean(beanName);
            }
        }
    }

这里主要关注普通bean的创建,进入AbstractBeanFactory中的getBean方法:

public Object getBean(String name) throws BeansException {
    // 获取Bean的实例
    return doGetBean(name, null, null, false);
}

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    // 获取bean名称
    final String beanName = transformedBeanName(name);
    Object bean;

    // 从缓存中获取单例bean
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) { //如果获取到单例bean,则走下面代码
        if (logger.isDebugEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.debug("Returning eagerly cached instance of singleton bean ‘" + beanName +
                             "‘ that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.debug("Returning cached instance of singleton bean ‘" + beanName + "‘");
            }
        }
        // 如果取出来的Bean实例是FactoryBean的Bean实例,则需要从FactoryBean实例中产生一个对象实例。
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {//如果没有获取到单例bean,则走下面代码

        // 如果原型模式的Bean发生循环引用,则直接不处理,抛出异常
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                    nameToLookup, requiredType, args, typeCheckOnly);
            }
            else if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }

        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }

        try {
            // 获取要实例化的bean的BeanDefinition对象
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            // 检查该BeanDefinition对象对应的Bean是否是抽象的
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "Circular depends-on relationship between ‘" + beanName + "‘ and ‘" + dep + "‘");
                    }
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "‘" + beanName + "‘ depends on missing bean ‘" + dep + "‘", ex);
                    }
                }
            }

            // 如果是单例的Bean,请下面的代码
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        // 创建单例Bean的主要方法
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }

            else if (mbd.isPrototype()) {
                // It‘s a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }

            else {
                String scopeName = mbd.getScope();
                final Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name ‘" + scopeName + "‘");
                }
                try {
                    Object scopedInstance = scope.get(beanName, () -> {
                        beforePrototypeCreation(beanName);
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        finally {
                            afterPrototypeCreation(beanName);
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                                                    "Scope ‘" + scopeName + "‘ is not active for the current thread; consider " +
                                                    "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                                    ex);
                }
            }
        }
        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }

这里主要关注单例Bean的的创建,进入AbstractAutowireCapableBeanFactory中的createBean方法,跳转到doCreateBean方法中,这里是进行bean创建的核心代码:

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    if (logger.isDebugEnabled()) {
        logger.debug("Creating instance of bean ‘" + beanName + "‘");
    }
    RootBeanDefinition mbdToUse = mbd;

    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    // 处理方法覆盖
    try {
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                                               beanName, "Validation of method overrides failed", ex);
    }

    try {
        // 获取BeanPostProcessor代理对象
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                                        "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
        // 完成Bean实例的创建(实例化、填充属性、初始化)
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean ‘" + beanName + "‘");
        }
        return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
    throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    // bean初始化第一步:默认调用无参构造实例化Bean
    // 构造参数依赖注入,就是发生在这一步
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // 实例化后的Bean对象
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // 解决循环依赖的关键步骤
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
    // 如果需要提前暴露单例Bean,则将该Bean放入三级缓存中
    if (earlySingletonExposure) {
        if (logger.isDebugEnabled()) {
            logger.debug("Eagerly caching bean ‘" + beanName + "‘ to allow for resolving potential circular references");
        }
        // 将刚创建的bean放入三级缓存中singleFactories(key是beanName,value是FactoryBean)
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // bean初始化第二步:填充属性(DI依赖注入发生在此步骤)
        populateBean(beanName, mbd, instanceWrapper);
        // bean初始化第三步:调用初始化方法,完成bean的初始化操作(AOP发生在此步骤)
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName, "...");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
}

这里通过三步实现Bean的创建,具体的实现会再后面文章进行说明。

Spring容器的初始化流程

标签:lan   mod   object c   pos   解决   查看   tee   epo   raw   

原文地址:https://www.cnblogs.com/liuyi6/p/10317120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!