Spring getBean方法源码解析

2023-11-15

User user = (User) beanFactory.getBean("user");

注:User为一普通bean

查看方法(AbstractBeanFactory#getBean

public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
}

继续查看方法(AbstractBeanFactory#doGetBean

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
                          @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    //一、提取beanName
    //这里主要做了两步工作
    //(1)去除name开头的所有&字符,即factoryBean的修饰符
    //(2)去aliasMap查找最终的beanName
    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    /*
		 * 这里是检查缓存中或者实例工厂中是否有对应的实例
		 * 原因:因为在创建单例bean的时候会存在依赖注入的情况。
		 * 而在创建依赖的时候为了避免循环依赖,Spring创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提早曝光,
		 * 也就是将ObjectFactory加入到缓存中,一旦下个bean创建的时候需要依赖上个bean则直接使用ObjectFactory
		 */
    //二、直接尝试从缓存获取或者从singletonFactories中的ObjectFactory
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                             "' that is not fully initialized yet - a consequence of a circular reference");
            }
            else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        //三、当前的sharedInstance只是原始的bean状态,这里需要进一步加工处理
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
    //四、如果没有找到,则直接创建实例
    else {
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        //只有在单例情况下才会尝试解决循环依赖
        //1、原型模式下,如果存在循环依赖,将会直接报错
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        // Check if bean definition exists in this factory.
        //2、如果所有已经加载的bean中不包括beanName,则尝试从parentBeanFactory中查找
        BeanFactory parentBeanFactory = getParentBeanFactory();
        //如果parentBeanFactory存在且当前的beanDefinitionMap不存在beanName的配置,
        //就只能调用parentBeanFactory的getBean方法去加载bean了
        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 if (requiredType != null) {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
            else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }

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

        //3、手动加载bean
        try {
            //将存储XML配置信息的GenericBeanDefinition转换成RootBeanDefinition,
            //如果BeanName是子Bean的话同时会合并父类的相关属性
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);

            // Guarantee initialization of beans that the current bean depends on.
            String[] dependsOn = mbd.getDependsOn();
            //如果存在依赖则需要定义实例化依赖的bean
            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
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            // Create bean instance.
            //实例化当前bean的所有依赖后便会实例化mbd本身了
            //下面是根据不同的scope类型来创建mbd

            //单例模式创建Bean
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        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;
        }
    }

    // Check if required type matches the type of the actual bean instance.
    //8、如果传递了类型,则需要进行类型转换
    if (requiredType != null && !requiredType.isInstance(bean)) {
        try {
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
            if (convertedBean == null) {
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
            return convertedBean;
        }
        catch (TypeMismatchException ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Failed to convert bean '" + name + "' to required type '" +
                             ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

上述方法就是获取bean的核心方法,我们一步一步拆解

一、首先我们需要对传递进来的name进行转换

代码如下:

protected String transformedBeanName(String name) {
    return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}

这里主要做了两件事

  • BeanFactoryUtils.transformedBeanName(name)

    public static String transformedBeanName(String name) {
        Assert.notNull(name, "'name' must not be null");
        if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
            return name;
        }
        return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
            do {
                beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
            }
            while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
            return beanName;
        });
    }
    

    该方法就是去除name的前缀中的所有&符号,这里的&符号主要是factoryBean的修饰符,如果name带有前缀&,表示获取当前的factoryBean,而非factoryBean返回的bean实例

  • canonicalName方法

    public String canonicalName(String name) {
        String canonicalName = name;
        // Handle aliasing...
        String resolvedName;
        do {
            resolvedName = this.aliasMap.get(canonicalName);
            if (resolvedName != null) {
                canonicalName = resolvedName;
            }
        }
        while (resolvedName != null);
        return canonicalName;
    }
    

    该方法就是去别名aliasMap中查找最终的beanName,例如aliasMap中,a->c,b->c,c不指向任何bean。那么当name输入a时返回的就是c。

二、尝试从缓存中加载bean

public Object getSingleton(String beanName) {
    //第二个参数true表示允许早期依赖
    return getSingleton(beanName, true);
}

进一步查看

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //检查缓存中是否存在实例
    Object singletonObject = this.singletonObjects.get(beanName);
    //如果为空且singletonsCurrentlyInCreation存在该bean
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
        //锁定singletonObjects全局变量
        synchronized (this.singletonObjects) {
            //从earlySingletonObjects获取bean
            singletonObject = this.earlySingletonObjects.get(beanName);
            //如果获取不到且允许早期依赖
            if (singletonObject == null && allowEarlyReference) {
                //从singletonFactories获取ObjectFactory,这是因为有时候某些方法需要提前初始化的时候会
                //调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletonFactories
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                //如果不为空
                if (singletonFactory != null) {
                    //调用预先设定的getObject方法
                    singletonObject = singletonFactory.getObject();
                    //记录在缓存中
                    this.earlySingletonObjects.put(beanName, singletonObject);
                    //earlySingletonObjects与singletonFactories是互斥的,因此这里需要remove
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }
    return singletonObject;
}

Spring创建bean默认情况下是单例的,因此对于一个单例bean,Spring只会创建一次,后续再获取时直接从缓存中加载。由于可能存在的循环依赖(例如A依赖B,B依赖A),因此Spring为了解决循环依赖,创建bean的原则是不等bean创建完成就将创建bean的ObjectFactory提早曝光到缓存中,一旦下一个bean创建时候需要时直接使用ObjectFactory。这里涉及到三级缓存

/** Cache of singleton objects: bean name to bean instance.
	 *  保存beanName和bean实例之间的关系,即beanName-->bean实例
	 */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

/** Cache of singleton factories: bean name to ObjectFactory.
	 *  保存beanName和创建bean的工厂之间的关系,即beanName-->ObjectFactory实例
	 */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

/** Cache of early singleton objects: bean name to bean instance.
	 *  保存beanName和bean实例之间的关系,即beanName-->bean实例
	 *  它与singletonObjects不同在于当一个bean被放到这里面后,即使bean还在创建中,也可以通过getBean获取到,
	 *  其目的就是检测循环依赖的
	 */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
  • singletonFactories(三级缓存):单例对象工厂的cache
  • earlySingletonObjects(二级缓存):提前曝光的单例对象的Cache 。用于检测循环引用,与singletonFactories互斥。
  • singletonObjects(一级缓存):单例对象的cache

上述方法执行流程如下

  • 首先从一级缓存singletonObjects中获取,如果获取到则直接返回,
  • 如果获取不到且对象也不是正在创建中,则直接返回null表示缓存中没有
  • 如果对象是正在创建中,则去到二级缓存earlySingletonObjects中进行查找,如果获取到直接返回
  • 如果获取不到且传递不允许早期依赖,直接返回null
  • 如果允许早期依赖,则进一步到三级缓存singletonFactories中查找
  • 如果未查询到,直接返回null
  • 如果查询到,则调用ObjectFactory的getObject方法获取对象,将对象放入二级缓存中,同时移除三级缓存。

三、如果从缓存中获取到了bean,则需要对获取到的bean进行加工处理

protected Object getObjectForBeanInstance(
    Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

    // Don't let calling code try to dereference the factory if the bean isn't a factory.
    //如果指定的name是工厂相关(以&作为前缀)
    if (BeanFactoryUtils.isFactoryDereference(name)) {
        if (beanInstance instanceof NullBean) {
            return beanInstance;
        }
        //如果beanInstance不是工厂类型,直接抛异常
        if (!(beanInstance instanceof FactoryBean)) {
            throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
        }
        if (mbd != null) {
            mbd.isFactoryBean = true;
        }
        return beanInstance;
    }

    // Now we have the bean instance, which may be a normal bean or a FactoryBean.
    // If it's a FactoryBean, we use it to create a bean instance, unless the
    // caller actually wants a reference to the factory.
    //如果不是工厂bean类型,则直接返回
    if (!(beanInstance instanceof FactoryBean)) {
        return beanInstance;
    }

    //执行到这里说明用户需要获得工厂对应的getObject方法返回的实例
    Object object = null;
    if (mbd != null) {
        mbd.isFactoryBean = true;
    }
    else {
        //从缓存中获取实例
        object = getCachedObjectForFactoryBean(beanName);
    }
    if (object == null) {
        // Return bean instance from factory.
        FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
        // Caches object obtained from FactoryBean if it is a singleton.
        if (mbd == null && containsBeanDefinition(beanName)) {
            mbd = getMergedLocalBeanDefinition(beanName);
        }
        boolean synthetic = (mbd != null && mbd.isSynthetic());
        object = getObjectFromFactoryBean(factory, beanName, !synthetic);
    }
    return object;
}
  • 如果name是&前缀,表示是获取FactoryBean的本体实例,直接返回当前实例
  • 如果name不是&前缀且当前bean不是工厂bean类型,则直接返回
  • 如果是工厂bean类型,则需要调用对应的getObject方法返回实例
    • 这里先从缓存factoryBeanObjectCache中获取,获取到直接返回
    • 如果获取不到才会调用getObject方法获取实例,同时放入factoryBeanObjectCache缓存中

四、如果从缓存中未获取到,则考虑直接创建实例

1、原型模式下的循环依赖检查

只有单例情况下才会尝试解决循环依赖,如果非单例模式,直接报错。

2、尝试使用parentBeanFactory加载

这里只有存在parentBeanFactory且beanDefinitionMap不存在beanName的配置,才不得不使用parentBeanFactory进行加载

3、手动加载当前bean(核心逻辑)

3.1、如果存在dependsOn的数据时,需要先递归实例化dependsOn中的类
3.2、创建当前bean(单例模式)
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    if (logger.isTraceEnabled()) {
        logger.trace("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    //解析出class类型
    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 {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        //给BeanPostProcessors一个机会来返回代理真正的实例(扩展作用)
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        //如果此时bean不为空,直接返回即可(该bean是通过BeanPostProcessors创建的)
        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.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        // A previously detected exception with proper bean creation context already,
        // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}

代码流程如下:

(1)首先解析出class类型
(2)重载方法的标记
(3)给BeanPostProcessors一个机会来返回代理真正的实例(扩展作用)

如果返回实例则直接返回。也就是说如果经过后置处理器返回的bean不为空,则直接略过后续的创建过程直接返回,代码如下

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    //如果尚未解析
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                //调用后置处理器的applyBeanPostProcessorsBeforeInstantiation方法
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    //调用后置处理器的applyBeanPostProcessorsAfterInitialization方法
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

逻辑很简单,无非就是调用后置处理器的applyBeanPostProcessorsBeforeInstantiationapplyBeanPostProcessorsAfterInitialization方法

(4)如果BeanPostProcessors处理并没有生成代理对象,则进行常规bean的创建

代码如下:

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);
    }
    if (instanceWrapper == null) {
        //根据指定的bean使用对应的策略创建新的实例(如:工厂方法、构造函数、简单初始化)
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    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;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    //满足以下三个条件才会调用方法addSingletonFactory
    //(1)单例
    //(2)允许循环依赖
    //(3)bean正在创建中
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                                      isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                         "' to allow for resolving potential circular references");
        }
        //添加bean的创建工厂到缓存中,目的是提前暴露,解决循环依赖
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        //属性填充
        populateBean(beanName, mbd, instanceWrapper);
        //初始化bean
        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,
                                                               "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.");
                }
            }
        }
    }

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

    return exposedObject;
}
(4.1)如果factoryBeanInstanceCache存在beanName,则取对应的bean实例,否则根据指定的bean使用对应的策略创建新的实例(如:工厂方法、构造函数、简单初始化)

代码如下

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    //解析class
    Class<?> beanClass = resolveBeanClass(mbd, beanName);

    //class校验(class不能为空且访问权限必须为public)
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }

    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }

    //如果工厂方法不为空,则使用工厂方法初始化策略
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }

    // Shortcut when re-creating the same bean...
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    //如果已经解析过则使用解析好的构造函数方法,无需再次锁定
    if (resolved) {
        if (autowireNecessary) {
            //构造函数自动注入
            return autowireConstructor(beanName, mbd, null, null);
        }
        else {
            //使用默认构造函数构造
            return instantiateBean(beanName, mbd);
        }
    }

    // Candidate constructors for autowiring?
    //如果未解析,需要根据参数解析构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        //构造函数自动注入
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // Preferred constructors for default construction?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    // No special handling: simply use no-arg constructor.
    //使用默认构造函数构造
    return instantiateBean(beanName, mbd);
}
  • 首先解析并校验当前的class类型

  • 如果RootBeanDefinition存在FactoryMethodName或者在配置文件中配置了factory-method,则使用instantiateUsingFactoryMethod来生成bean

  • 解析构造函数并使用构造函数反射生成实例(这里使用了RootBeanDefinition的缓存机制,即解析过的构造方法保存到RootBeanDefinition的属性中,下次直接取缓存)。构造函数实例化分为两种,一种是无参构造函数,一种是有参构造函数。

    有参构造函数创建实例代码如下

    public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
                                           @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
    
        BeanWrapperImpl bw = new BeanWrapperImpl();
        this.beanFactory.initBeanWrapper(bw);
    
        Constructor<?> constructorToUse = null;
        ArgumentsHolder argsHolderToUse = null;
        Object[] argsToUse = null;
    
        //explicitArgs通过getBean方法传入
        //如果指定则直接使用指定的参数
        if (explicitArgs != null) {
            argsToUse = explicitArgs;
        }
        //如果没有指定则尝试从缓存中获取
        else {
            Object[] argsToResolve = null;
            //尝试从缓存获取
            synchronized (mbd.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                    // Found a cached constructor...
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            //如果缓存存在
            if (argsToResolve != null) {
                //解析参数,包含可能的参数类型转换
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
            }
        }
        //如果没有缓存
        if (constructorToUse == null || argsToUse == null) {
            // Take specified constructors, if any.
            Constructor<?>[] candidates = chosenCtors;
            if (candidates == null) {
                Class<?> beanClass = mbd.getBeanClass();
                try {
                    candidates = (mbd.isNonPublicAccessAllowed() ?
                                  beanClass.getDeclaredConstructors() : beanClass.getConstructors());
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                    "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                                                    "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                }
            }
    
            if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
                Constructor<?> uniqueCandidate = candidates[0];
                if (uniqueCandidate.getParameterCount() == 0) {
                    synchronized (mbd.constructorArgumentLock) {
                        mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                        mbd.constructorArgumentsResolved = true;
                        mbd.resolvedConstructorArguments = EMPTY_ARGS;
                    }
                    bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                    return bw;
                }
            }
    
            // Need to resolve the constructor.
            boolean autowiring = (chosenCtors != null ||
                                  mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
            ConstructorArgumentValues resolvedValues = null;
    
            int minNrOfArgs;
            if (explicitArgs != null) {
                minNrOfArgs = explicitArgs.length;
            }
            else {
                //提取配置文件中配置的构造函数参数
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                //存放解析后的构造函数的参数值
                resolvedValues = new ConstructorArgumentValues();
                //记录解析到的最小参数的数量
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            }
    
            //排序给定的构造函数,public构造函数优先参数数量降序,非public构造函数参数数量降序
            AutowireUtils.sortConstructors(candidates);
            int minTypeDiffWeight = Integer.MAX_VALUE;
            Set<Constructor<?>> ambiguousConstructors = null;
            LinkedList<UnsatisfiedDependencyException> causes = null;
    
            for (Constructor<?> candidate : candidates) {
                Class<?>[] paramTypes = candidate.getParameterTypes();
    
                //如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止(因此上面已经按照参数个数降序排列)
                if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
                    // Already found greedy constructor that can be satisfied ->
                    // do not look any further, there are only less greedy constructors left.
                    break;
                }
                //参数个数不相等,跳过当前循环
                if (paramTypes.length < minNrOfArgs) {
                    continue;
                }
    
                ArgumentsHolder argsHolder;
                if (resolvedValues != null) {
                    //有参数则根据值构造对应参数类型的参数
                    try {
                        String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                        if (paramNames == null) {
                            //注释上获取参数名称
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                                //获取指定构造函数的参数名称
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
                        //根据名称和数据类型创建参数持有者
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                                                         getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                    }
                    catch (UnsatisfiedDependencyException ex) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                        }
                        // Swallow and try next constructor.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        causes.add(ex);
                        continue;
                    }
                }
                else {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }
                    //构造函数没有参数的情况
                    argsHolder = new ArgumentsHolder(explicitArgs);
                }
    
                //探测是否有不确定性的构造函数存在,例如不同构造函数的参数为父子关系
                int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
                                      argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
                // Choose this constructor if it represents the closest match.
                //如果它代表当前最接近的匹配则选择作为构造函数
                if (typeDiffWeight < minTypeDiffWeight) {
                    constructorToUse = candidate;
                    argsHolderToUse = argsHolder;
                    argsToUse = argsHolder.arguments;
                    minTypeDiffWeight = typeDiffWeight;
                    ambiguousConstructors = null;
                }
                else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                    if (ambiguousConstructors == null) {
                        ambiguousConstructors = new LinkedHashSet<>();
                        ambiguousConstructors.add(constructorToUse);
                    }
                    ambiguousConstructors.add(candidate);
                }
            }
    
            if (constructorToUse == null) {
                if (causes != null) {
                    UnsatisfiedDependencyException ex = causes.removeLast();
                    for (Exception cause : causes) {
                        this.beanFactory.onSuppressedException(cause);
                    }
                    throw ex;
                }
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                "Could not resolve matching constructor " +
                                                "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
            }
            else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                "Ambiguous constructor matches found in bean '" + beanName + "' " +
                                                "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
                                                ambiguousConstructors);
            }
    
            if (explicitArgs == null && argsHolderToUse != null) {
                //将解析的构造函数加入缓存
                argsHolderToUse.storeCache(mbd, constructorToUse);
            }
        }
    
        Assert.state(argsToUse != null, "Unresolved constructor arguments");
        //将构造的实例加入到BeanWrapper中
        bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
        return bw;
    }
    
    • 首先需要确定构造函数的参数,这里有三个方式获取
      • 根据explicitArgs参数判断
      • 直接从缓存中取
      • 配置文件中取
    • 根据构造函数参数确定构造函数
    • 根据确定的构造函数转换对应的参数类型
    • 构造函数的不确定性验证
    • 根据实例化策略以及得到的构造函数及构造函数参数数理化bean

    无参构造函数实例化如下

    protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            final BeanFactory parent = this;
            if (System.getSecurityManager() != null) {
                beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                                                             getInstantiationStrategy().instantiate(mbd, beanName, parent),
                                                             getAccessControlContext());
            }
            else {
                beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
            }
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);
            initBeanWrapper(bw);
            return bw;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
        }
    }
    

    Spring直接调用实例化策略,无需进行参数解析,逻辑相对简单。

    前面我们只说了解析构造器然后实例化,接下来我们查看具体的实例化代码

    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        // Don't override the class with CGLIB if no overrides.
        //如果不存在方法的替换,直接反射即可,无需使用CGLIB进行动态代理
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    final Class<?> clazz = bd.getBeanClass();
                    if (clazz.isInterface()) {
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(
                                (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                        }
                        else {
                            constructorToUse = clazz.getDeclaredConstructor();
                        }
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    }
                    catch (Throwable ex) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                    }
                }
            }
            return BeanUtils.instantiateClass(constructorToUse);
        }
        //使用CGLIB生成代理类
        else {
            // Must generate CGLIB subclass.
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }
    
    • 如果存在方法的替换,则需要使用CGLIB生成代理类
    • 否则直接构造器反射生成实例
(4.2)如果当前bean是单例,且允许循环依赖,且在处在创建的过程中,则会讲当前bean放到三级缓存中,目的是提前暴露,解决循环依赖。

代码段如下

//满足以下三个条件才会调用方法addSingletonFactory
//(1)单例
//(2)允许循环依赖
//(3)bean正在创建中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                                  isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
    if (logger.isTraceEnabled()) {
        logger.trace("Eagerly caching bean '" + beanName +
                     "' to allow for resolving potential circular references");
    }
    //添加bean的创建工厂到缓存中,目的是提前暴露,解决循环依赖
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

此处是解决循环依赖的关键。当bean通过构造器反射生成实例时,如果是单例模式,且允许循环依赖,则会讲当前bean放入到三级缓存中,提前暴露。我们来看下getEarlyBeanReference方法

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            //SmartInstantiationAwareBeanPostProcessor处理
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
            }
        }
    }
    return exposedObject;
}

调用SmartInstantiationAwareBeanPostProcessor类型的后置处理器处理bean

(4.3)注意此时的bean只是利用构造方法进行反射获取的bean,还不是一个完整的bean,因此需要进行属性填充,方法如下
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    if (bw == null) {
        if (mbd.hasPropertyValues()) {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            // Skip property population phase for null instance.
            return;
        }
    }

    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    // 给InstantiationAwareBeanPostProcessors最后一次机会在属性设置前来改变bean
    // 例如可以用来支持属性注入的类型
    boolean continueWithPropertyPopulation = true;

    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }

    //如果后置处理器发出停止填充命令则终止后续的执行
    if (!continueWithPropertyPopulation) {
        return;
    }

    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        //根据名称注入
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        //根据类型注入
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        //依赖检查
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        //将属性应用到bean中
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

解析bean中的依赖,如果必要,会递归调用getBean()方法获取所依赖的bean。

处理流程如下:

  • InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法来控制是否继续进行属性填充
  • 根据名称注入或者类型进行注入
  • 应用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法对属性获取完毕填充前对属性的再次处理。
  • 将所有的PropertyValues中的属性填充到BeanWrapper中

我们再来查看一下注入逻辑

  • autowireByName(根据名称注入)

    protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    
        //获取所有需要依赖注入的属性
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            if (containsBean(propertyName)) {
                //递归初始化相关bean
                Object bean = getBean(propertyName);
                pvs.add(propertyName, bean);
                //注册依赖
                registerDependentBean(propertyName, beanName);
                if (logger.isTraceEnabled()) {
                    logger.trace("Added autowiring by name from bean name '" + beanName +
                                 "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
                }
            }
            else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                                 "' by name: no matching bean found");
                }
            }
        }
    }
    

    根据属性名递归加载bean并加入到pvs中

  • autowireByType(根据类型注入)

    protected void autowireByType(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
    
        Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
        //在bw中查找需要依赖注入的属性
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            try {
                PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
                // Don't try autowiring by type for type Object: never makes sense,
                // even if it technically is a unsatisfied, non-simple property.
                if (Object.class != pd.getPropertyType()) {
                    //获取指定属性的set方法
                    MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                    // Do not allow eager init for type matching in case of a prioritized post-processor.
                    boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                    DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                    //解析指定的依赖,并把解析到的属性名称存储在autowiredBeanNames中
                    Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                    if (autowiredArgument != null) {
                        pvs.add(propertyName, autowiredArgument);
                    }
                    for (String autowiredBeanName : autowiredBeanNames) {
                        //注册依赖
                        registerDependentBean(autowiredBeanName, beanName);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
                                         propertyName + "' to bean named '" + autowiredBeanName + "'");
                        }
                    }
                    autowiredBeanNames.clear();
                }
            }
            catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
          }
        }
    }
    

    逻辑较为简单,根据属性的类型解析出对应依赖并放入pvs中,核心逻辑是resolveDependency方法,代码如下

    public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
                                    @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    
        descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
        //Optional类型的特殊处理
        if (Optional.class == descriptor.getDependencyType()) {
            return createOptionalDependency(descriptor, requestingBeanName);
        }
        //ObjectFactory类型的特殊处理
        else if (ObjectFactory.class == descriptor.getDependencyType() ||
                 ObjectProvider.class == descriptor.getDependencyType()) {
            return new DependencyObjectProvider(descriptor, requestingBeanName);
        }
        //javaxInjectProviderClass的特殊处理
        else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
            return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
        }
    
        //常规处理
        else {
            Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                descriptor, requestingBeanName);
            if (result == null) {
                result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
            }
            return result;
        }
    }
    

    首先对一些特殊的类型进行处理,最后的再进行常规依赖的处理(细节后续再研究)

  • 依赖解析完成,最后将属性应用到bean中,对应方法为applyPropertyValues

    protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
        if (pvs.isEmpty()) {
            return;
        }
    
        if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
            ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
        }
    
        MutablePropertyValues mpvs = null;
        List<PropertyValue> original;
    
        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues) pvs;
            if (mpvs.isConverted()) {
                // Shortcut: use the pre-converted values as-is.
                try {
                    bw.setPropertyValues(mpvs);
                    return;
                }
                catch (BeansException ex) {
                    throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Error setting property values", ex);
                }
            }
            original = mpvs.getPropertyValueList();
        }
        else {
            original = Arrays.asList(pvs.getPropertyValues());
        }
    
        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
        BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    
        // Create a deep copy, resolving any references for values.
        List<PropertyValue> deepCopy = new ArrayList<>(original.size());
        boolean resolveNecessary = false;
        //遍历属性,将属性转换为对应类的对应属性的类型
        for (PropertyValue pv : original) {
            if (pv.isConverted()) {
                deepCopy.add(pv);
            }
            else {
                String propertyName = pv.getName();
                Object originalValue = pv.getValue();
                if (originalValue == AutowiredPropertyMarker.INSTANCE) {
                    Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
                    if (writeMethod == null) {
                        throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
                    }
                    originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
                }
                Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
                Object convertedValue = resolvedValue;
                boolean convertible = bw.isWritableProperty(propertyName) &&
                    !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
                if (convertible) {
                    convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
                }
                // Possibly store converted value in merged bean definition,
                // in order to avoid re-conversion for every created bean instance.
                if (resolvedValue == originalValue) {
                    if (convertible) {
                        pv.setConvertedValue(convertedValue);
                    }
                    deepCopy.add(pv);
                }
                else if (convertible && originalValue instanceof TypedStringValue &&
                         !((TypedStringValue) originalValue).isDynamic() &&
                         !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                    pv.setConvertedValue(convertedValue);
                    deepCopy.add(pv);
                }
                else {
                    resolveNecessary = true;
                    deepCopy.add(new PropertyValue(pv, convertedValue));
                }
            }
        }
        if (mpvs != null && !resolveNecessary) {
            mpvs.setConverted();
        }
    
        // Set our (possibly massaged) deep copy.
        try {
            bw.setPropertyValues(new MutablePropertyValues(deepCopy));
        }
        catch (BeansException ex) {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
        }
    }
    

    遍历属性,将属性转换为对应类的对应属性的类型。

(4.4)此时bean的属性填充完成,这时候需要对bean做一些用户自定义的初始化的工作

代码如下

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        //1、对特殊的bean处理:Aware、BeanClassLoaderAware、BeanFactoryAware
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        //2、应用后处理器
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        //3、激活用户自定义的init方法
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        //4、后处理器应用
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

该方法主要做了以下几件事

  • Aware接口处理,可以获取对应的资源,即如果bean实现了类似BeanClassLoaderAware、BeanFactoryAware接口,需要组装相应的属性

    private void invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            //BeanNameAware处理
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            //BeanClassLoaderAware处理
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            //BeanFactoryAware处理
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }
    
  • 调用BeanPostProcessor的postProcessBeforeInitialization方法

  • 调用用户自定义的init方法

  • 调用BeanPostProcessor的postProcessAfterInitialization方法

(4.5)循环依赖检查

这块是循环依赖的检测,代码如下

//满足以下三个条件才earlySingletonExposure才会为true
//(1)单例
//(2)允许循环依赖
//(3)bean正在创建中
if (earlySingletonExposure) {
    //从二级缓存中获取当前bean
    Object earlySingletonReference = getSingleton(beanName, false);
    if (earlySingletonReference != null) {
        if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
        }
        //allowRawInjectionDespiteWrapping 标注是否允许此Bean的原始类型被注入到其它Bean里面,即使自己最终会被包装(代理)
        //默认是false,即不允许
        //如果allowRawInjectionDespiteWrapping为false且当前bean存在被依赖的bean
        //此处为二级缓存的bean与exposedObject不相同,因此需要找到当前bean所被依赖的bean,
        //一旦存在则说明其他bean依赖了当前bean的二级缓存的引用,而非最终bean的引用,所以肯定存在问题
        else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
            //获取当前bean依赖的bean集合
            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,
                                                           "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.");
            }
        }
    }
}

逻辑详见注释。

(4.6)注册DisposabeBean

Spring提供了销毁bean的方法,我们可以在配置文件的配置对应的destroy-method,也可以使用注册DestructionAwareBeanPostProcessor来统一处理bean的销毁方法

(4.7)完成创建返回
3.3、创建当前bean(原型模式)

直接创建实例,不放入缓存。创建实例同上述createBean方法。

3.4、创建当前bean(其余模式)

其余模式,直接创建实例并放入到对应的scope中其余模式,直接创建实例并放入到对应的scope中。创建实例同上述createBean方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring getBean方法源码解析 的相关文章

随机推荐

  • 纷玩岛演唱会下单代码

    继大麦M端之后 再发现一个演唱会平台 纷玩岛 此平台不像大麦 猫眼那么火爆 相对来说比较容易研究 通过抓包软件发现下单很简单 就一个JWT登录后的头部token而已 下载地址 https download csdn net download
  • 结构体对函数指针的高级封装应用

    分层设计考虑 作用 降低对底层应用程序的高耦合度 示例 include mac h typedef struct phy t char channel char snd fail count char name char open flag
  • 软件测试用例覆盖率怎么算,如何计算增量测试覆盖率

    为了保证代码质量 一般会要求提交的源码要有测试用例覆盖 并对测试覆盖率有一定的要求 在实践中不仅会考核存量代码覆盖率 总体覆盖率 还会考核增量代码的覆盖率 或者说增量覆盖率更有实际意义 测试用例要随源码一并提交 实时保证源码的质量 而不是代
  • 进程和线程的区别,以及应用场景

    什么是线程 Linux下线程用进程PCB模拟描述 也叫轻量级进程 线程是进程内部的一个执行流 也就是线程在进程的地址空间内运行 一个进程内的所有线程共享进程资源 线程是CPU调度的基本单位 CPU调度是按照PCB进行调度的 创建 销毁一个线
  • Mule入门——DB、Rest、Soap接口开发

    一 DB查询接口开发 这里我用的mysql数据库 首先我们先查询下我们的数据库这里有很多数据 然后我们用AnypointStudio进行我们的接口开发 首先我们先新建一个Mule工程 File gt New gt Mule project
  • 计算机网络---传输层

    两个端的会话层之间提供建立 维护和取消传输连接的功能 这一层 数据传送的协议单元成为报文 网络层只是根据网络地址将源节点发出的数据包送到目的终点 而传输层负责将数据可靠的传送到相应的端口 传输层负责将上层数据分段提供端到端 可靠不可靠的传输
  • vue3-admin-template页面

    vue3 admin template 本人学习视频网址为 视频地址 源码 github 网页采用技术框架 本管理模板采用vue3开发 使用vue router来作为路由跳转 将登录成功后产生的菜单 token放入到vuex中存储 通过ax
  • 一般Python开发面试中可能会问到的大部分问题

    python语法以及其他基础部分 可变与不可变类型 浅拷贝与深拷贝的实现方式 区别 deepcopy如果你来设计 如何实现 new 与 init 的区别 你知道几种设计模式 编码和解码你了解过么 列表推导list comprehension
  • Linux嵌入式学习——c语言选择结构设计

    Linux嵌入式学习 c语言选择结构设计 一 if语句 1 1if语句的一般格式 1 2if语句常用的3种形式 1 3if语句的嵌套 二 关系运算符和关系表达式 2 1关系运算符及其优先次序 2 2关系表达式 三 逻辑运算符和逻辑表达式 3
  • @ControllerAdvice注解使用及原理探究

    最近在新项目的开发过程中 遇到了个问题 需要将一些异常的业务流程返回给前端 需要提供给前端不同的响应码 前端再在次基础上做提示语言的国际化适配 这些异常流程涉及业务层和控制层的各个地方 如果每个地方都写一些重复代码显得很冗余 然后查询解决方
  • PowerBI入门学习笔记

    下载安装 Win10系统 在微软商店里直接下载PowerBI desktop 打开即可 界面如下 接下来导入后面要用到的数据 我目前用的都是Excel文件 获取数据 选中后选择要导入的若干个工作表 点击 加载数据 就进入到power que
  • vue+element实现双向描点 反向联动

    前端项目里经常会有锚点得操作 以及反向联动的效果 就是一个菜单 点击会定位到一个块上 滚动的当前块的时候 菜单会出现定位的效果 差不多就是这种动起来的效果 由于不太懂之前的逻辑 今天又从重新看了下 上代码 html 滚动的区域
  • 关于Python中pip install 各种包下载不下来的问题解决办法

    你们有可能报安装不成功或者下面这个问题 已经安装了但并非在你的Python安装路径下 C Users xxx gt pip install ddt Requirement already satisfied ddt in e anacond
  • redis 实现乐观锁

    redis是单线程程序但是支持多进程同时访问同一个redis服务 这个时候就需要锁机制来处理一些并发问题 redis提供了watch指令来实现乐观锁 watch和事务配合使用 往往写在multi之前 用来监视一个key 比如watch mo
  • 实战wxPython:047 - Book控件(第一部分)

    在wxPython中 book控件允许用户在各种面板之间切换 最常见的例子是带有选项卡界面的浏览器和系统选项对话框 本文将向您介绍这些控件的创建和基本配置 wxPython目前内置了多个这样的控件 除文章 wxPython 高级控件之选项卡
  • 看完这篇 教你玩转渗透测试靶机Vulnhub——Grotesque:3.0.1

    Vulnhub靶机Grotesque 3 0 1渗透测试详解 Vulnhub靶机介绍 Vulnhub靶机下载 Vulnhub靶机安装 信息收集 漏洞发现 LFI漏洞利用 本地文件包含漏洞 SSH登入 提权 获取FLAG Vulnhub靶机渗
  • pyqt 万能简易模板(四)

    本文将介绍一些pyqt5基本使用技巧 不借助Qtdesigner 而是全部用代码编写 将实现页面布局 窗口自适应 字体自适应等功能 一般的简易工程均可使用 简单高效 对于pyqt5的一些基本技巧 本文内容基本够用 可以快速实现自己想要的界面
  • Java中的如何检测字符串是否相等

    文章目录 0 写在前面 1 介绍 2 举例 3 写在后面 0 写在前面 实际业务中有时候得检测字符串是否相等的场景 例如在数据库中提取uuid 检测两个uuid是否相等就需要用到这个地方 1 介绍 可以使用equals方法检测两个字符串是否
  • 数据预处理、特征工程和特征学习

    神经网络的数据预处理 数据预处理的目的是使原始数据更适于用神经网络处理 包括向量化 标准化 处理缺失值和特征提取 1 向量化 神经网络的所有输入和目标都必须是浮点数张量 特定情况下为整数张量 无论处理什么数据 都必须先将其转换为张量 这一步
  • Spring getBean方法源码解析

    User user User beanFactory getBean user 注 User为一普通bean 查看方法 AbstractBeanFactory getBean public Object getBean String nam