Spring源码之doGetBean

我们知道spring里面IOC就是通过doGetBean来工作的,这个方法在AbstractBeanFactory类里面,从字面意思我们就能知道这是一个工厂类。下面我们来看看里面到底是怎么工作的。

protected  T doGetBean(String name, Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
        final String beanName = this.transformedBeanName(name);//解析beanName 因为如果是FactoryBean会带上&符号
        Object sharedInstance = this.getSingleton(beanName);//尝试从缓存中获取单例bean
        Object bean;
        if(sharedInstance != null && args == null) {//如果已经存在
            ·····
            bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);//主要是对FactoryBean进行处理
        } else {
            BeanFactory ex = this.getParentBeanFactory();
            if(ex != null && !this.containsBeanDefinition(beanName)) {//父bean工厂进行生产
                String var24 = this.originalBeanName(name);
                if(args != null) {
                    return ex.getBean(var24, args);
                }

                return ex.getBean(var24, requiredType);
            }

            if(!typeCheckOnly) {
                this.markBeanAsCreated(beanName);//把bean添加到标识准备好创建的list
            }

            try {
                final RootBeanDefinition ex1 = this.getMergedLocalBeanDefinition(beanName);// 生成简单beanDefintion
                this.checkMergedBeanDefinition(ex1, beanName, args);
                String[] dependsOn = ex1.getDependsOn();//获取它的依赖bean
                String[] scopeName;
                if(dependsOn != null) {
                    scopeName = dependsOn;
                    int scope = dependsOn.length;

                    for(int ex2 = 0; ex2 < scope; ++ex2) {//循环生产所依赖的bean
                        String dependsOnBean = scopeName[ex2];
                        this.getBean(dependsOnBean);
                        this.registerDependentBean(dependsOnBean, beanName);//注册到依赖bean集合
                    }
                }

                if(ex1.isSingleton()) {//判断是否单例
                    sharedInstance = this.getSingleton(beanName, new ObjectFactory() {
                        public Object getObject() throws BeansException {
                            try {
                                return AbstractBeanFactory.this.createBean(beanName, ex1, args);//真正生成bean的方法,这里会对循环依赖问题进行处理
                            } catch (BeansException var2) {
                                AbstractBeanFactory.this.destroySingleton(beanName);
                                throw var2;
                            }
                        }
                    });
                    bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, ex1);
                } else if(ex1.isPrototype()) {
                    scopeName = null;

                    Object var25;
                    try {
                        this.beforePrototypeCreation(beanName);
                        var25 = this.createBean(beanName, ex1, args);
                    } finally {
                        this.afterPrototypeCreation(beanName);
                    }

                    bean = this.getObjectForBeanInstance(var25, name, beanName, ex1);
                } else {
                    String var26 = ex1.getScope();
                    Scope var27 = (Scope)this.scopes.get(var26);
                    if(var27 == null) {
                        throw new IllegalStateException("No Scope registered for scope \'" + var26 + "\'");
                    }

                    try {
                        Object var28 = var27.get(beanName, new ObjectFactory() {
                            public Object getObject() throws BeansException {
                                AbstractBeanFactory.this.beforePrototypeCreation(beanName);

                                Object var1;
                                try {
                                    var1 = AbstractBeanFactory.this.createBean(beanName, ex1, args);
                                } finally {
                                    AbstractBeanFactory.this.afterPrototypeCreation(beanName);
                                }

                                return var1;
                            }
                        });
                        bean = this.getObjectForBeanInstance(var28, name, beanName, ex1);
                    } catch (IllegalStateException var21) {
                        throw new BeanCreationException(beanName, "Scope \'" + var26 + "\' 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", var21);
                    }
                }
            } catch (BeansException var23) {
                this.cleanupAfterBeanCreationFailure(beanName);
                throw var23;
            }
        }

        if(requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
            try {
                return this.getTypeConverter().convertIfNecessary(bean, requiredType);
            } catch (TypeMismatchException var22) {
                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("Failed to convert bean \'" + name + "\' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", var22);
                }

                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        } else {
            return bean;
        }
    }
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
        Map var3 = this.singletonObjects;
        synchronized(this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if(singletonObject == null) {
                ···
                try {
                    singletonObject = singletonFactory.getObject();//获取bean
                } catch (BeanCreationException var14) {
                    BeanCreationException ex = var14;
                    if(recordSuppressedExceptions) {
                        Iterator i$ = this.suppressedExceptions.iterator();

                        while(i$.hasNext()) {
                            Exception suppressedException = (Exception)i$.next();
                            ex.addRelatedCause(suppressedException);
                        }
                    }

                    throw ex;
                } finally {
                    if(recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                }

                this.addSingleton(beanName, singletonObject);//添加到单例缓存map
            }

            return singletonObject != NULL_OBJECT?singletonObject:null;
        }
    }
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        this.resolveBeanClass(mbd, beanName, new Class[0]);

        try {
            mbd.prepareMethodOverrides();
        } catch (BeanDefinitionValidationException var5) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", var5);
        }

        Object beanInstance;
        try {
            beanInstance = this.resolveBeforeInstantiation(beanName, mbd);//开始初始化工作
            if(beanInstance != null) {
                return beanInstance;
            }
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var6);
        }

        beanInstance = this.doCreateBean(beanName, mbd, args);//生产bean
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Finished creating instance of bean \'" + beanName + "\'");
        }

        return beanInstance;
    }
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if(!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            if(mbd.hasBeanClass() && !mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
                bean = this.applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);//对实现InstantiationAwareBeanPostProcessor接口的bean进行初始化
                if(bean != null) {
                    bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);//执行beanPostProcessor的AfterInitialization方法 
                }
            }

            mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null);
        }

        return bean;
    }
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args) {
        BeanWrapper instanceWrapper = null;
        if(mbd.isSingleton()) {
            instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
        }

        if(instanceWrapper == null) {
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }

        final Object bean = instanceWrapper != null?instanceWrapper.getWrappedInstance():null;
        Class beanType = instanceWrapper != null?instanceWrapper.getWrappedClass():null;
        Object earlySingletonExposure = mbd.postProcessingLock;
        synchronized(mbd.postProcessingLock) {
            if(!mbd.postProcessed) {
                this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);//对实现MergedBeanDefinitionPostProcessor接口的bean进行处理
                mbd.postProcessed = true;
            }
        }

        boolean var19 = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
        if(var19) {
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Eagerly caching bean \'" + beanName + "\' to allow for resolving potential circular references");
            }

            this.addSingletonFactory(beanName, new ObjectFactory() {
                public Object getObject() throws BeansException {
                    return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean);
                }
            });
        }

        Object exposedObject = bean;

        try {
            this.populateBean(beanName, mbd, instanceWrapper);//设置属性
            if(exposedObject != null) {
                exposedObject = this.initializeBean(beanName, exposedObject, mbd);//初始化bean 先执行BeanPostProcessor的BeforeInitialization方法 然后如果这个bean实现了InitializingBean接口则执行afterPropertiesSet方法  然后执行init-method方法 最后执行BeanPostProcessor的AfterInitialization方法
            }
        } catch (Throwable var17) {
            if(var17 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var17).getBeanName())) {
                throw (BeanCreationException)var17;
            }

            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var17);
        }

        if(var19) {
            Object ex = this.getSingleton(beanName, false);
            if(ex != null) {
                if(exposedObject == bean) {
                    exposedObject = ex;
                } else if(!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                    String[] dependentBeans = this.getDependentBeans(beanName);
                    LinkedHashSet actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                    String[] arr$ = dependentBeans;
                    int len$ = dependentBeans.length;

                    for(int i$ = 0; i$ < len$; ++i$) {
                        String dependentBean = arr$[i$];
                        if(!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }

                    if(!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName, "Bean with name \'" + beanName + "\' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "\'getBeanNamesOfType\' with the \'allowEagerInit\' flag turned off, for example.");
                    }
                }
            }
        }

        try {
            this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
            return exposedObject;
        } catch (BeanDefinitionValidationException var16) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
        }
    }

你可能感兴趣的:(Spring源码之doGetBean)