Spring Bean创建过程解析

准备

  • Spring版本:5.0.8

时序图

先上时序图帮助理解 Bean 实例创建过程
Bean实例创建过程

解析过程

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) applicationContext.getBean("person");

首先从 getBean() 方法开始创建过程,getBean()有一系列的重载方法,最终都是调用doGetBean() 方法

// AbstractAutowireCapableBeanFactory 471
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
    String beanName = this.transformedBeanName(name);
// 首先尝试从缓存获取单例bean
    Object sharedInstance = this.getSingleton(beanName);
    Object bean;
    if (sharedInstance != null && args == null) {
        if (this.logger.isDebugEnabled()) {
            if (this.isSingletonCurrentlyInCreation(beanName)) {
                this.logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
            } else {
                this.logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        // 获取给定bean的实例对象 如果是FactoryBean需要进行相关处理
        bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
    } else {
    // 只有在单例情况下会去解决循环依赖,原型模式下,如果存在A中有B属性,B中有A属性,依赖注入时
    // 会产生A还没创建完因为对于B的创建再次返回创建A,造成循环依赖,因此对于这种情况直接抛出异常
        if (this.isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        BeanFactory parentBeanFactory = this.getParentBeanFactory();
    // 检查当前BeanFactory是否存在需要创建实例的BeanDefinition 如果不存在 则委托父级容器加载
        if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
            String nameToLookup = this.originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
            }

            if (args != null) {
                return parentBeanFactory.getBean(nameToLookup, args);
            }

            return parentBeanFactory.getBean(nameToLookup, requiredType);
        }
        // 判断创建的bean是否需要进行类型验证
        if (!typeCheckOnly) {
        // 向容器标记指定的bean实例已经创建
            this.markBeanAsCreated(beanName);
        }

        try {
        // 根据指定bean名称获取父级BeanDefinition 解决bean继承时子类合并父类公共属性问题
            RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
            this.checkMergedBeanDefinition(mbd, beanName, args);
      // 获取当前bean所有依赖bean的名称
            String[] dependsOn = mbd.getDependsOn();
            String[] var11;
            if (dependsOn != null) {
                var11 = dependsOn;
                int var12 = dependsOn.length;

                for(int var13 = 0; var13 < var12; ++var13) {
                    String dep = var11[var13];
                    if (this.isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    // 为当前bean注册依赖bean 以便当前bean销毁前先销毁依赖bean
                    this.registerDependentBean(dep, beanName);

                    try {
                    // 创建依赖bean
                        this.getBean(dep);
                    } catch (NoSuchBeanDefinitionException var24) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", var24);
                    }
                }
            }

            if (mbd.isSingleton()) {
            // 单例bean 且 缓存不存在
                sharedInstance = this.getSingleton(beanName, () -> {
                    try {
                    // 创建bean
                        return this.createBean(beanName, mbd, args);
                    } catch (BeansException var5) {
                        this.destroySingleton(beanName);
                        throw var5;
                    }
                });
            // 获取给定bean的实例对象 如果是FactoryBean需要进行相关处理
                bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            } else if (mbd.isPrototype()) {
                var11 = null;

                Object prototypeInstance;
                try {
                // 回调beforePrototypeCreation方法 默认实现是注册当前创建的原型对象
                    this.beforePrototypeCreation(beanName);
                // 创建bean
                    prototypeInstance = this.createBean(beanName, mbd, args);
                } finally {
                // 回调afterPrototypeCreation方法 默认实现告诉IoC容器指定Bean的原型对象不再创建
                    this.afterPrototypeCreation(beanName);
                }
                // 获取给定bean的实例对象 如果是FactoryBean需要进行相关处理
                bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
            // 其它scope类型处理
                String scopeName = mbd.getScope();
                Scope 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, () -> {
                        this.beforePrototypeCreation(beanName);

                        Object var4;
                        try {
                        // 创建bean
                            var4 = this.createBean(beanName, mbd, args);
                        } finally {
                            this.afterPrototypeCreation(beanName);
                        }

                        return var4;
                    });
                    bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                } catch (IllegalStateException var23) {
                    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", var23);
                }
            }
        } catch (BeansException var26) {
            this.cleanupAfterBeanCreationFailure(beanName);
            throw var26;
        }
    }
    // 如果需要对创建的bean实例进行类型检查
    if (requiredType != null && !requiredType.isInstance(bean)) {
        try {
            T convertedBean = this.getTypeConverter().convertIfNecessary(bean, requiredType);
            if (convertedBean == null) {
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            } else {
                return convertedBean;
            }
        } catch (TypeMismatchException var25) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", var25);
            }

            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    } else {
        return bean;
    }
}

通过 getSingleton 方法尝试从缓存中获取单例 bean

// DefaultSingletonBeanRegistry
@Nullable
public Object getSingleton(String beanName) {
    // 参数true 代表允许提前依赖 
    return this.getSingleton(beanName, true);
}

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 首先从缓存获取单例bean
    Object singletonObject = this.singletonObjects.get(beanName);
// 如果缓存为空且当前bean在创建中
    if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
        Map var4 = this.singletonObjects;
        synchronized(this.singletonObjects) {
        // 从提前加载的bean集合获取
            singletonObject = this.earlySingletonObjects.get(beanName);
        // 如果缓存为空且允许提前依赖
            if (singletonObject == null && allowEarlyReference) {
            // 获取单例bean工厂
                ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                // 单例bean工厂不为空 则创建bean实例
                    singletonObject = singletonFactory.getObject();
                // 添加到提前加载bean缓存中
                    this.earlySingletonObjects.put(beanName, singletonObject);
                // 将单例bean工厂移除 因为已经调用工厂加载bean实例 无需再次调用
                    this.singletonFactories.remove(beanName);
                }
            }
        }
    }

    return singletonObject;
}
// AbstractBeanFactory
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
     // 如果指定的name是工厂bean(以&作为前缀)
     if (BeanFactoryUtils.isFactoryDereference(name)) {
        if (beanInstance instanceof NullBean) {
            return beanInstance;
        }
        // 类型不是工厂bean类型 抛出异常
        if (!(beanInstance instanceof FactoryBean)) {
            throw new BeanIsNotAFactoryException(this.transformedBeanName(name), beanInstance.getClass());
        }
    }
    // 如果当前bean是工厂bean类型 且 指定name不是工厂bean相关(以&为前缀)
    if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
        // 加载FactoryBean
        Object object = null;
        if (mbd == null) {
            // 尝试从缓存中加载bean
            object = this.getCachedObjectForFactoryBean(beanName);
        }

        if (object == null) {
            FactoryBean<?> factory = (FactoryBean)beanInstance;
            // 检查当前beanDefinitionMap是否存在当前beanName
            if (mbd == null && this.containsBeanDefinition(beanName)) {
                // 如果bean是子bean合并父类相关属性
                mbd = this.getMergedLocalBeanDefinition(beanName);
            }
            // 是否是用户定义的而不是应用程序本身定义的
            boolean synthetic = mbd != null && mbd.isSynthetic();
            object = this.getObjectFromFactoryBean(factory, beanName, !synthetic);
        }

        return object;
    } else {
        return beanInstance;
    }
}
// FactoryBeanRegistrySupport
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && this.containsSingleton(beanName)) { // 单例
        synchronized(this.getSingletonMutex()) {
        // 尝试从缓存中获取FactoryBean
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (object == null) {
            // 从FactoryBean中获取bean
                object = this.doGetObjectFromFactoryBean(factory, beanName);
            // 再次尝试从缓存中获取 因为自定义bean处理循环依赖时已经放入缓存中
                Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
                if (alreadyThere != null) {
                    object = alreadyThere;
                } else {
                    if (shouldPostProcess) {
                        if (this.isSingletonCurrentlyInCreation(beanName)) {
                            return object;
                        }

                        this.beforeSingletonCreation(beanName);

                        try {
                            object = this.postProcessObjectFromFactoryBean(object, beanName);
                        } catch (Throwable var14) {
                            throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", var14);
                        } finally {
                            this.afterSingletonCreation(beanName);
                        }
                    }

                    if (this.containsSingleton(beanName)) {
                        this.factoryBeanObjectCache.put(beanName, object);
                    }
                }
            }

            return object;
        }
    } else {
    // 从FactoryBean中获取bean
        Object object = this.doGetObjectFromFactoryBean(factory, beanName);
        if (shouldPostProcess) {
            try {
                object = this.postProcessObjectFromFactoryBean(object, beanName);
            } catch (Throwable var17) {
                throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", var17);
            }
        }

        return object;
    }
}
// FactoryBeanRegistrySupport
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
    Object object;
    try {
        // 需要权限验证
        if (System.getSecurityManager() != null) {
            AccessControlContext acc = this.getAccessControlContext();

            try {
                object = AccessController.doPrivileged(factory::getObject, acc);
            } catch (PrivilegedActionException var6) {
                throw var6.getException();
            }
        } else {
            // 直接调用getObject方法
            object = factory.getObject();
        }
    } catch (FactoryBeanNotInitializedException var7) {
        throw new BeanCurrentlyInCreationException(beanName, var7.toString());
    } catch (Throwable var8) {
        throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", var8);
    }

    if (object == null) {
        if (this.isSingletonCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject");
        }

        object = new NullBean();
    }

    return object;
}

当前 bean 是单例且缓存不存在则通过 getSingleton(String beanName, ObjectFactory<?> singletonFactory) 方法创建单例对象

// DefaultSingletonBeanRegistry
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "Bean name must not be null");
    Map var3 = this.singletonObjects;
// 同步加锁
    synchronized(this.singletonObjects) {
    // 首先尝试从缓存中获取
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
        // 单例bean正在销毁则抛出异常
            if (this.singletonsCurrentlyInDestruction) {
                throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)");
            }

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
            }
            // 单例bean创建前的前置处理
            this.beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = this.suppressedExceptions == null;
            if (recordSuppressedExceptions) {
                this.suppressedExceptions = new LinkedHashSet();
            }

            try {
            // 初始化bean
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            } catch (IllegalStateException var16) {
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) {
                    throw var16;
                }
            } catch (BeanCreationException var17) {
                BeanCreationException ex = var17;
                if (recordSuppressedExceptions) {
                    Iterator var8 = this.suppressedExceptions.iterator();

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

                throw ex;
            } finally {
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = null;
                }
                // 单例bean创建后的后置处理
                this.afterSingletonCreation(beanName);
            }

            if (newSingleton) {
            // 将结果添加至缓存
                this.addSingleton(beanName, singletonObject);
            }
        }

        return singletonObject;
    }
}

上述方法第二个参数 ObjectFactory 使用了匿名内部类,并调用了 createBean 方法

// AbstractAutowireCapableBeanFactory
@Override
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 根据设置的class属性或者根据className解析Class
   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }

   // 验证及准备覆盖的方法
   try {
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
            beanName, "Validation of method overrides failed", ex);
   }

   try {
      // 给BeanPostProcessors机会返回代理对象替代真正实例对象
      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 {
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isDebugEnabled()) {
         logger.debug("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);
   }
}
// AbstractAutowireCapableBeanFactory
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);
   }
   //由createBeanInstance方法创建Bean
   if (instanceWrapper == null) {
      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 {
            // 应用MergedBeanDefinitionPostProcessors修改合并BeanDefinition
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Post-processing of merged bean definition failed", ex);
         }
         mbd.postProcessed = true;
      }
   }

   //是否需要提前曝光 单例 且 允许循环依赖 且 当前bean正在创建中 检查循环依赖
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
         logger.debug("Eagerly caching bean '" + beanName +
               "' to allow for resolving potential circular references");
      }
      // 为避免后期循环依赖 可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      // 对bean进行填充 属性注入
      populateBean(beanName, mbd, instanceWrapper);
      // 调用初始化方法 如init-method
      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 {
      // 注册DisposableBean
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
   }

   return exposedObject;
}

主要包含下下面三个主要方法:

  • createBeanInstance
  • populateBean
  • initializeBean

createBeanInstance 方法用于创建 Bean 实例

// AbstractAutowireCapableBeanFactory
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // 检查确认bean是可实例化的
Class<?> beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
    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());
    } else {
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return this.obtainFromSupplier(instanceSupplier, beanName);
        } else if (mbd.getFactoryMethodName() != null) {
        // 使用工厂方法实例化bean对象
            return this.instantiateUsingFactoryMethod(beanName, mbd, args);
        } else {
            boolean resolved = false;
            boolean autowireNecessary = false;
            if (args == null) {
                Object var8 = mbd.constructorArgumentLock;
                synchronized(mbd.constructorArgumentLock) {
                    if (mbd.resolvedConstructorOrFactoryMethod != null) {
                        resolved = true;
                        autowireNecessary = mbd.constructorArgumentsResolved;
                    }
                }
            }

            if (resolved) {
            // 配置自动装配属性 使用容器的自动装配实例化 否则使用默认无参构造方法实例化 
                return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);
            } else {
            // 使用bean的构造方法进行实例化 默认使用无参构造方法 如果配置了容器自动装配 则调用匹配的构造方法实例化
                Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
                return ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args) ? this.instantiateBean(beanName, mbd) : this.autowireConstructor(beanName, mbd, ctors, args);
            }
        }
    }
}
// ConstructorResolver
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
// 初始化BeanWrapper 添加属性编辑器
    this.beanFactory.initBeanWrapper(bw);
    Constructor<?> constructorToUse = null;
    ConstructorResolver.ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;
    Object beanInstance;
    if (explicitArgs != null) {
    // 如果传入了方法参数 则直接使用
        argsToUse = explicitArgs;
    } else {
    // 否则从配置文件中解析获取方法参数
        Object[] argsToResolve = null;
        beanInstance = mbd.constructorArgumentLock;
        synchronized(mbd.constructorArgumentLock) {
            constructorToUse = (Constructor)mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
            // 首先尝试从缓存中获取
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                // 配置的构造函数
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }

        if (argsToResolve != null) { // 如果缓存中存在
        // 解析参数列表(类型转换)给制定的构造方法
            argsToUse = this.resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
        }
    }

    if (constructorToUse == null) { // 没有被缓存
        boolean autowiring = chosenCtors != null || mbd.getResolvedAutowireMode() == 3;
        ConstructorArgumentValues resolvedValues = null;
        int minNrOfArgs;
        if (explicitArgs != null) { // 传入了参数列表
            minNrOfArgs = explicitArgs.length;
        } else {
        // 提取配置文件中配置的构造方法参数
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
        // 用于保存解析后构造方法参数的值
            resolvedValues = new ConstructorArgumentValues();
        // 解析的参数个数
            minNrOfArgs = this.resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }

        Constructor<?>[] candidates = chosenCtors;
        if (chosenCtors == null) {
            Class beanClass = mbd.getBeanClass();

            try {
                candidates = mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors();
            } catch (Throwable var25) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", var25);
            }
        }
        // 排序给定的构造方法 public优先 根据参数数量降序
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = 2147483647;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;
        Constructor[] var16 = candidates;
        int var17 = candidates.length;

        for(int var18 = 0; var18 < var17; ++var18) {
            Constructor<?> candidate = var16[var18];
            Class<?>[] paramTypes = candidate.getParameterTypes();
            if (constructorToUse != null && argsToUse.length > paramTypes.length) {
            // 如果已经找到选用的构造方法或者需要的参数个数小于当前构造方法参数个数则终止 因为已经按照参数个数降序排列
                break;
            }

            if (paramTypes.length >= minNrOfArgs) {
                ConstructorResolver.ArgumentsHolder argsHolder;
                if (resolvedValues != null) {
            // 有参数则根据值构造对应参数类型的参数
                    try {
                    // 首先尝试从@ConstructorProperties注解上获取参数名称
                        String[] paramNames = ConstructorResolver.ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                        if (paramNames == null) {
                        // 获取参数名称探测器(通过反射技术获取参数名称)
                            ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                            if (pnd != null) {
                            // 获取制定构造方法的参数名称
                                paramNames = pnd.getParameterNames(candidate);
                            }
                        }
                        // 根据名称和数据类型创建参数数组
                        argsHolder = this.createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, this.getUserDeclaredConstructor(candidate), autowiring);
                    } catch (UnsatisfiedDependencyException var26) {
                        if (this.logger.isTraceEnabled()) {
                            this.logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + var26);
                        }

                        if (causes == null) {
                            causes = new LinkedList();
                        }

                        causes.add(var26);
                        continue;
                    }
                } else {
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }

                    argsHolder = new ConstructorResolver.ArgumentsHolder(explicitArgs);
                }
                // 获取参数匹配的权重 权重越小匹配度越高
                int typeDiffWeight = mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes);
                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) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
            }

            UnsatisfiedDependencyException ex = (UnsatisfiedDependencyException)causes.removeLast();
            Iterator var34 = causes.iterator();

            while(var34.hasNext()) {
                Exception cause = (Exception)var34.next();
                this.beanFactory.onSuppressedException(cause);
            }

            throw ex;
        }

        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.storeCache(mbd, constructorToUse);
        }
    }

    try {
        InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(() -> {
                return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
            }, this.beanFactory.getAccessControlContext());
        } else {
        // 根据选中的构造方法实例化bean
            beanInstance = strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }
        放入包装类中返回
        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable var24) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", var24);
    }
}
// AbstractAutowireCapableBeanFactory
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(() -> {
                return thisx.getInstantiationStrategy().instantiate(mbd, beanName, this);
            }, this.getAccessControlContext());
        } else {
            beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this);
        }

        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        this.initBeanWrapper(bw);
        return bw;
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", var6);
    }
}
// SimpleInstantiationStrategy
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果没有需要覆盖或者动态替换的方法则直接使用反射 否则使用cglib动态代理并将动态方法织入类中
    if (!bd.hasMethodOverrides()) {
        Object var5 = bd.constructorArgumentLock;
        Constructor constructorToUse;
        synchronized(bd.constructorArgumentLock) {
            constructorToUse = (Constructor)bd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse == null) {
                Class<?> clazz = bd.getBeanClass();
                if (clazz.isInterface()) {
                    throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }

                try {
                    if (System.getSecurityManager() != null) {
                        clazz.getClass();
                        constructorToUse = (Constructor)AccessController.doPrivileged(() -> {
                            return clazz.getDeclaredConstructor();
                        });
                    } else {
                        constructorToUse = clazz.getDeclaredConstructor();
                    }

                    bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                } catch (Throwable var9) {
                    throw new BeanInstantiationException(clazz, "No default constructor found", var9);
                }
            }
        }
        // 使用反射使用指定构造方法实例化对象
        return BeanUtils.instantiateClass(constructorToUse, new Object[0]);
    } else {
    // 使用cglib动态代理生成代理类对象
        return this.instantiateWithMethodInjection(bd, beanName, owner);
    }
}
// CglibSubclassingInstantiationStrategy
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner, @Nullable Constructor<?> ctor, @Nullable Object... args) {
    return (new CglibSubclassingInstantiationStrategy.CglibSubclassCreator(bd, owner)).instantiate(ctor, args);
}
// CglibSubclassingInstantiationStrategy.CglibSubclassCreator
public Object instantiate(@Nullable Constructor<?> ctor, @Nullable Object... args) {
    Class<?> subclass = this.createEnhancedSubclass(this.beanDefinition);
    Object instance;
    if (ctor == null) {
        instance = BeanUtils.instantiateClass(subclass);
    } else {
        try {
            Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
            instance = enhancedSubclassConstructor.newInstance(args);
        } catch (Exception var6) {
            throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", var6);
        }
    }

    Factory factory = (Factory)instance;
    factory.setCallbacks(new Callback[]{NoOp.INSTANCE, new CglibSubclassingInstantiationStrategy.LookupOverrideMethodInterceptor(this.beanDefinition, this.owner), new CglibSubclassingInstantiationStrategy.ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
    return instance;
}

populateBean 方法主要给 Bean 进行属性注入

// AbstractAutowireCapableBeanFactory
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.
   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);
   //开始进行依赖注入过程,先处理autowired注入
   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

      // Add property values based on autowire by name if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }

      // Add property values based on autowire by type if applicable.
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }

      pvs = newPvs;
   }

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

   if (hasInstAwareBpps || needsDepCheck) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
      if (needsDepCheck) {
         checkDependencies(beanName, mbd, filteredPds, pvs);
      }
   }

   if (pvs != null) {
      //对属性进行注入
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

initializeBean 方法主要处理各种回调

// AbstractAutowireCapableBeanFactory
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 {
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      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()) {
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}

至此,整个 Bean 创建过程完成。

参考资料

Spring源码深度解析
Spring技术内幕:深入解析Spring架构与设计原理
https://blog.csdn.net/heroqiang/article/details/78683060

猜你喜欢

转载自blog.csdn.net/laravelshao/article/details/82318063