6、Spring BeanFactory创建对象之源码解读

前言

前面的文章我们提到过,XmlBeanFactory创建获取对象方式如下:

public void test() throws InterruptedException, ExecutionException {
    //这里是解析xml文件并封装成BeanDefinition,然后注册存储起来,存在Spring容器中。
    XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
    //这里是Spring根据上一步存储起来的BeanDefinition帮我们创建对象的地方。因为所有创建对象所需要的信息都存在于BeanDefinition中。
    User user = (User) xmlBeanFactory.getBean("user");
}

创建对象的过程就是我们利用工程getBean的过程,而创建过成包括 创建对象 --- 属性填充 --- 初始化 等一系列流程,这个流程在上篇文章有详细讲解。

创建对象源码的解析

接下来我们来解析 xmlBeanFactory.getBean("user") 的源码:

//先调用的是这个方法
public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}

//由上一个方法跳转到这个方法,这个方法才是创建对象的核心
//参数 name:想获取的beanName,
//参数 requiredType:想获取的bean的类型
//参数 args:
//参数 typeCheckOnly:
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
    
   //转换beanName,转换的原因是:咱们传过来的name有可能是别名,此时这里就需要转换,拿到其真正的id
   //如果咱们传过来的name前面有个 &, 这说明我们想获取的是个FactoryBean类型的实例,他会把&去掉。
   //这步作用就是:获取bean真正的id值。
   String beanName = transformedBeanName(name);
   Object bean;

   //从单例池中获取曾经创建过的缓存bean对象,如果对象初次创建时,肯定获取不到。
   //这里也是一个重点,里面涉及到了三级缓存的概念。
   //从缓存中获取bean,共有三级缓存,先从singletonObjects(一级缓存)中获取,再从earlySingletonObjects(二级缓存)获取,最后从singletonFactories(三级缓存获取)
   //spring设计这三级缓存的目的就是为了解决循环引用的问题。
   //Spring创建对象时,这个对象共有两种状态:完全状态(对象已经创建完成)、正在创建中的状态(对象还没有完全创建,正处在某个阶段,可能是初始化,可能是属性填充)
   Object sharedInstance = getSingleton(beanName);
   
   //如果能从缓存中获取bean,走如下这段代码
   if (sharedInstance != null && args == null) {
      if (logger.isTraceEnabled()) {
          //判断这个bean是否正在创建,
         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 + "'");
         }
      }
      //将从缓存池中获得的对象,进行普通对象和FactoryBean接口对象的区分,如果是普通对象 则直接返回给调用者,如果是FactoryBean接口的实现,则调用getObject方法返回。
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }

   else {
      //如果这个对象正在创建并且是prototype类型的时候,就抛异常,
      //此处实际上是个校验代码
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }

      //下面的代码是解决父子容器的问题
      //获取父容器 如果有父容器且这个配置在子容器中没有
      //那么实例化父容器对应的bean(递归)
      BeanFactory parentBeanFactory = getParentBeanFactory();
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         // Not found -> check parent.
         String nameToLookup = originalBeanName(name);
         if (parentBeanFactory instanceof AbstractBeanFactory) {
            return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                  nameToLookup, requiredType, args, typeCheckOnly);
         }
         else if (args != null) {
            // Delegation to parent with explicit args.
            return (T) parentBeanFactory.getBean(nameToLookup, args);
         }
         else if (requiredType != null) {
            // No args -> delegate to standard getBean method.
            return parentBeanFactory.getBean(nameToLookup, requiredType);
         }
         else {
            return (T) parentBeanFactory.getBean(nameToLookup);
         }
      }
        
      //typeCheckOnly默认是false,所以此代码块肯定执行,
      //实际上这块代码的含义是将这个bean进行一个标记,标记的状态有:
      //如果typeCheckOnly为true:spring只是对获取类型进行判断而并不是创建对象,例如:beanFactory.getBean("u",User.class),spring是不会创建User对象的,而是判断当前工厂获得或者创建的对象类型是不是User类型
      //如果typeCheckOnly为false:spring会创建对象
      //注意:typeCheckOnly无论是true还是false,都只是对这个bean进行一个状态的标记,无论是创建对象,还是校验类型,都是后面的代码进行操作的。
      if (!typeCheckOnly) {
          //标记这个bean是需要创建对象而不是类型检查,具体怎么标记的分为如下两步:
          //1.这个方法内部的 clearMergedBeanDefinition(beanName)方法:bean标签是有继承关系的,有父子标签的存在的,MergedBeanDefinition就是将父子bean标签里面的内容进行合并,最终将得出一个RootBeanDefinition
          //而这步需要做的就是将这个bean标记成需要被融合的状态,这个状态作为在下面代码的try块中是否可以进行融合的依据。
          //2.这个方法内部的 this.alreadyCreated.add(beanName)方法:将这个bean加入到alreadyCreated(正在创建的集合里)
         markBeanAsCreated(beanName);
      }

      try {
          
          //进行父子bean的融合
          //父bean:<bean id="p" abstract=true"/>
          //子bean:<bean id="u" class="xxx.xxx" parent="p"/>
          //父子进行融合,融合成了 RootBeanDefinition
         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         //对融合后的bd进行检验:防止工厂都是抽象bean
         checkMergedBeanDefinition(mbd, beanName, args);

         //保证初始化当前bean所依赖的bean。也就是在这里处理 depends-on 属性。
         String[] dependsOn = mbd.getDependsOn();
         if (dependsOn != null) {
            for (String dep : dependsOn) {
               if (isDependent(beanName, dep)) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
               }
               registerDependentBean(dep, beanName);
               try {
                  getBean(dep);
               }
               catch (NoSuchBeanDefinitionException ex) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
               }
            }
         }
         
         //核心
         // 从这里开始创建对象,这里包含了if ->else if -> else 代码块。
         //if块中处理单例对象,else if 块处理多实例对象 ,else块是处理其他作用域对象的。
         //此处创建单例对象的细节流程请看后面的详细讲解部分,因为细节太多
         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);
               //调用createBean创建对象
               prototypeInstance = createBean(beanName, mbd, args);
            }
            finally {
               //清除标记信息。
               afterPrototypeCreation(beanName);
            }
            //获取真正的对象返回给调用者
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         }

         else {
            String scopeName = mbd.getScope();
            if (!StringUtils.hasLength(scopeName)) {
               throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
            }
            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.
   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;
}

由于上面的代码太多,接下来我会将其分成一块一块的来解读。

getSingleton 核心源码

此部分是上面doGetBean方法中的专门创建singleton类型bean的代码块,接下来我们对这个代码块进行解读。

//mbd就是合并完父子bean之后得到的RootBeanDefiniton,这个里面记录了创建bean的详细信息,其中就包括开发者想创建的是否是一个singleton类型的bean
if (mbd.isSingleton()) {
    //这里是一个lambda函数,先会调用getSingleton方法,而方法内部,会回调createBean方法。
   sharedInstance = getSingleton(beanName, () -> {
      try {
         return createBean(beanName, mbd, args);
      }
      catch (BeansException ex) {
         //这里的作用是:因为捕获到了异常,需要清除所有关于此bean的信息,
         destroySingleton(beanName);
         throw ex;
      }
   });
   bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

接下来讲解上面的lambda函数getSingleton方法,解析源码:

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
   Assert.notNull(beanName, "Bean name must not be null");
   //加锁:防止并发访问,锁住的是一级缓存map
   synchronized (this.singletonObjects) {
       //再次确认此时的单例池(一级缓存)中没有这个bean
      Object singletonObject = this.singletonObjects.get(beanName);
      
      //如果这个bean不存在,走如下if块代码:
      if (singletonObject == null) {
          //这里再次加一个校验,意思是:判断这个bean是否是正在销毁状态,如果在销毁状态下,这个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 (logger.isDebugEnabled()) {
            logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
         }
         //核心1:这里做了两个判断,判断如下:
         //1.这个bean没有被排除:在我们基于注解开发过程中会在启动类或者配置类上加上@ComponentScan()注解,而注解有个属性excludeFilters,这个属性代表着告诉spring不注册哪些bean,也就是排除哪些bean
         //基于标签也可以配置排除策略。
         //2.这个bean此时正在被创建:将这个bean添加到正在创建bean的set集合中。这个操作主要是为了解决循环依赖的问题,如果其他bean以来了这个bean,那个其他bean就不需要再重新创建了。
         beforeSingletonCreation(beanName);
         boolean newSingleton = false;
         boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
         if (recordSuppressedExceptions) {
            this.suppressedExceptions = new LinkedHashSet<>();
         }
         try {
            //核心2:这个方法就是回调lambda中的createBean方法
            singletonObject = singletonFactory.getObject();
            newSingleton = true;
         }
         catch (IllegalStateException ex) {
            // Has the singleton object implicitly appeared in the meantime ->
            // if yes, proceed with it since the exception indicates that state.
            singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
               throw ex;
            }
         }
         catch (BeanCreationException ex) {
            if (recordSuppressedExceptions) {
               for (Exception suppressedException : this.suppressedExceptions) {
                  ex.addRelatedCause(suppressedException);
               }
            }
            throw ex;
         }
         finally {
            if (recordSuppressedExceptions) {
               this.suppressedExceptions = null;
            }
            //核心3:创建完成之后该干的事情,包括清空一些标志性的数据
            afterSingletonCreation(beanName);
         }
         if (newSingleton) {
            //如果这个bean是单例的,就会将这个bean放到单例池(singletonObjects)中
            addSingleton(beanName, singletonObject);
         }
      }
      return singletonObject;
   }
}

核心1的所有细节我已经用注释写的很清楚了,详细阅读即可。

createBean 核心源码

接下来我们来讲解核心2 singletonObject = singletonFactory.getObject() 的源码:

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;

   //resolveBeanClass方法和接下来的if块的核心就是:获取这个bean的class对象
   //spring创建对象时基于反射创建的,而反射创建对象就需要有这个类的class对象。
   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }

   // 这个try,catch是解决replace(方法替换)的,目前来说没什么用。
   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.
      //上面spring注释的意思是:给BeanPostProcessors一个返回代理而不是目标bean实例的机会。
      //这里就不做详细分析了,因为这里99%的概率不会执行
      //不执行的原因:如果这里成功返回代理对象了,后续的所有实例化对象的代码直接就都不会走了,因为下面的if块,如果bean!=null 就直接返回了,就没有后续了。
      //所以这里不用关注。大家可以各自debug试验一下。
      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.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);
   }
}
doCreateBean:

核心源码createBean中的doCreateBean:

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

   // Instantiate the bean.
   //这个是定义一个这个bean的包装对象,这个BeanWrapper既存储了对象本身,又存储了对象属性所需要的类型转换器,关于类型转换器的概念和自定义方式,你自己学去吧。
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
       //将这个bean从factoryBeanInstanceCache这个map中移除
       //实例化后的bean在这个map中会有记录,所以第一次创建的时候,这个移除操作返回的wrapper是空的。
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
       //核心1:完成对象的创建
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   //获取实例的bean
   Object bean = instanceWrapper.getWrappedInstance();
   //获取实例bean的类型
   Class<?> beanType = instanceWrapper.getWrappedClass();
   //BeanDefinition里bean的类型和wrapper中bean的类型校验
   if (beanType != NullBean.class) {
      mbd.resolvedTargetType = beanType;
   }

   // Allow post-processors to modify the merged bean definition.(允许后处理程序修改合并后的bean定义。)
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            //核心2:
            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.
   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");
      }
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      //核心:属性的填充 set注入
      populateBean(beanName, mbd, instanceWrapper);
      //核心:初始化操作
      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 " +
                     "'getBeanNamesForType' 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;
}
createBeanInstance 核心源码:

核心源码createBean中的doCreateBean中createBeanInstance源码:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   // Make sure bean class is actually resolved at this point.
   //确保bean类在这一点上得到了真正的解析。
   Class<?> beanClass = resolveBeanClass(mbd, beanName);

   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);
   }
   
   //核心1:这里解析的是bean标签中的实例工厂和静态工厂的那个属性
   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.
   //核心2:通过反射的方式调用类默认的无参构造创建对象
   return instantiateBean(beanName, mbd);
}
populateBean 核心源码:

核心源码createBean中的doCreateBean中populateBean源码:

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.
   //省略
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               return;
            }
         }
      }
   }
   //获取bean的属性字段信息
   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
   //省略:outowire没人用,不做解析
   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;
   }
   
   //定义一个标志:这个表示你用的是注解的形式进行的注入,逻辑会走下面的if块,哪个if块自己往下找。
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   //定义一个标志:看后续是否需要校验,一般是不开的
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

   PropertyDescriptor[] filteredPds = null;
   //基于注解方式进行属性的注入
   if (hasInstAwareBpps) {
      if (pvs == null) {
         //获取所有需要注入的属性PropertyValue
         pvs = mbd.getPropertyValues();
      }
      //通过BeanPostProcessor的形式完成基于注解形式的注入
      //这里用的是AutowiredAnnotationBeanPostProcessor
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
          //AutowiredAnnotationBeanPostProcessor是InstantiationAwareBeanPostProcessor的一个子类
          //InstantiationAwareBeanPostProcessor这个类的不同子类分别代表了不同的注解,言外之意就是(举2个例子):
          //1.如果这个bean用了@Autowired,那么这个地方就会用AutowiredAnnotationBeanPostProcessor来处理,也就是循环到这个processor是就会进入if处理
          //2.如果这个bean用了@Configuration这个注解,那么这个地方就会由ConfigurationClassPostProcessor来处理,循环到了这个processor时就会进行处理
         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) {
      //非注解的属性填充
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

核心源码createBean中的doCreateBean中populateBean中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());
   }
   //解析xml时所有的propertyValue都会声明成MutablePropertyValue,所以这个就是代表所有的PropertyValues
   MutablePropertyValues mpvs = null;
   //原始的PropertyValues:没有进行类型转换的
   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);
         }
      }
      //解析MutablePropertyValues的核心在这里:就是将MutablePropertyValues填充到original中
      original = mpvs.getPropertyValueList();
   }
   else {
      original = Arrays.asList(pvs.getPropertyValues());
   }
   //获取自定义转换器
   TypeConverter converter = getCustomTypeConverter();
   if (converter == null) {
      converter = bw;
   }
   
   //根据这些参数,得到一个BeanDefinitionValue的处理器的工具
   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;
   
   //遍历所有PropertyValue属性:此处拿xml中int类型的id ,值为 "1"举例
   for (PropertyValue pv : original) {
       //这里默认情况不会走,因为我们没有自定义类型转换器
      if (pv.isConverted()) {
         deepCopy.add(pv);
      }
      else {
          //原始的属性名字
         String propertyName = pv.getName();
         //原始的属性值:
         //基本数据类型:原始的value被spring封装成了TypeStringValue类型,
         //自定义的数据类型(例如:注入一个user类型):原始的value被spring封装成了RuntimeBeanReference类型
         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);
         }
         
         //转换工作:
         //如果是TypedStringValue类型:将TypeStringValue转换成 "1"
         //如果是 RuntimeBeanReference类型:从工厂中获得user对象,获取方式为:beanFactory.getBean(BeanName),而走到这一步,那么又会重新走一遍getBean流程,这里属于一个递归
         Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
         Object convertedValue = resolvedValue;
         boolean convertible = bw.isWritableProperty(propertyName) &&
               !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
         if (convertible) {
             //这里将"1"转换成 int类型的 1
            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))) {
            //这里将 int类型的 1 ,赋值给PropertyValue
            pv.setConvertedValue(convertedValue);
            //一个一个的属性转换完成之后,会存储在deepCopy中,后面会将这个再统一赋值给BeanDefinitionWrapper
            deepCopy.add(pv);
         }
         else {
            resolveNecessary = true;
            deepCopy.add(new PropertyValue(pv, convertedValue));
         }
      }
   }
   if (mpvs != null && !resolveNecessary) {
       //打个标记:所有PropertyValue都已经转换完了
      mpvs.setConverted();
   }

   // Set our (possibly massaged) deep copy.
   try {
      //将所有转换后的PropertyValue赋值给bw
      bw.setPropertyValues(new MutablePropertyValues(deepCopy));
   }
   catch (BeansException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Error setting property values", ex);
   }
}
initializeBean 核心源码:

核心源码createBean中的doCreateBean中initializeBean源码:

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
   //安全校验:省略
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      //处理各种Aware,包括BeanNameAware、BeanFactoryAware、BeanClassLoaderAware
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      //处理咱们自定义类中实现的BeanPostProcessor中的 postProcessBeforeInitialization方法
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      //执行初始化方法,两种定义初始化方法的方式:1 、
      //1.实现接口
      //2.在xml中添加init-method属性,指定初始化方法
      //注意:如果这两种都应用了,那么先执行实现接口的方式
      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()) {
      处理咱们自定义类中实现的BeanPostProcessor中的 postProcessorsAfterInitialization方法
      //注意:也是在这一步进行的Aop代理
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}

总结:

希望大家按照层级结构来观看源码:

这里的方法是一层套一层,简直就是一个套娃。建议边看笔记边看源码效果会更好一些。

  1. getSingleton
    1. createBean
      1. doCreateBean
        1. createBeanInstance
        2. populateBean
        3. initializeBean

这里主要讲的是创建singleton类型的bean,而prototype类型的bean就比singleton少了getSingleton的步骤

singleton是先调用的getSingleton,在getSingleton里面调用的createBean,而prototype是直接调用的createBean。

最后还有其他类型的scope,源码大家自行阅读。这篇文章的所有细节都已经在注释中了,希望大家详细感受每行代码的意思,如果不仔细看,后面会越看越蒙蔽的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值