spring 源码核心方法之 finishBeanFactoryInitialization(beanFactory)解析(六)

今天我们讲解spring 启动过程中最核心方法,我们计划分多篇讲解,今天解析该方法的主干核心,后几篇我们解析该方法相关的分支方法(为啥啊?因为这个方法太重要了!),废话少说,看源码!

1、来到   AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext  类的

refresh()  方法

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      try {
    //删除以前解析过的源码
         /*
         * 这个方法是spring中最重要的方法,没有之一
         * 因此这个方法一定要详细分析,主要有一下几点功能:
         * 1、bean实例化过程,实例化所有的(非惰性初始化)单例。
         * 2、ioc 容器,循环依赖注入
         * 3、类中各种注解的支持
         * 4、BeanPostProcessor的执行
         * 5、Aop动态代理的入口处
         * */
         finishBeanFactoryInitialization(beanFactory);//点击进入
         // Last step: publish corresponding event.
         finishRefresh();
      }
      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }
         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();
         // Reset 'active' flag.
         cancelRefresh(ex);
         // Propagate exception to caller.
         throw ex;
      }
      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {

   //设置类型转换器
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }

    //如果没有bean后处理器,注册一个默认的嵌入式值解析器
    //(例如PropertyPlaceholderConfigurer bean)以前注册过:
    //此时,主要用于解析注释属性值。
   //先简单看看
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }

   // 尽早初始化LoadTimeWeaverAware bean,以便尽早注册它们的转换器。先简单看看
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // 停止使用临时类加载器进行类型匹配。先简单看看
   beanFactory.setTempClassLoader(null);

   // 允许缓存所有的bean定义元数据,不期望有进一步的更改。先简单看看
   beanFactory.freezeConfiguration();

   //重点看这个方法,实例化所有剩余的(非惰性初始化)单例。
   beanFactory.preInstantiateSingletons();//点击进入
}

2、ctrl+t 进入  DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable   类中

@Override
public void preInstantiateSingletons() throws BeansException {
   if (logger.isTraceEnabled()) {
      logger.trace("Pre-instantiating singletons in " + this);
   }

   //前几篇 讲解  xml解析时讲过,把所有beanName都缓存到beanDefinitionNames了
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // 触发所有非惰性单例bean的初始化...
   for (String beanName : beanNames) {
      //把父BeanDefinition里面的属性拿到子子类BeanDefinition中,可以进去先看看,不难
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);

      //如果不是抽象的,单例的,非懒加载的就实例化
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {

         //判断bean是否实现了FactoryBean接口,这里自己看看,后面会详细讲解
         if (isFactoryBean(beanName)) {
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
            if (bean instanceof FactoryBean) {
               final FactoryBean<?> factory = (FactoryBean<?>) bean;
               boolean isEagerInit;
               if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                  isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                              ((SmartFactoryBean<?>) factory)::isEagerInit,
                        getAccessControlContext());
               }
               else {
                  isEagerInit = (factory instanceof SmartFactoryBean &&
                        ((SmartFactoryBean<?>) factory).isEagerInit());
               }
               if (isEagerInit) {
                  getBean(beanName);
               }
            }
         }
         else {
            //主要核心从这里进入,看看实例化过程,点击进入
            getBean(beanName);
         }
      }
   }

   // 所有适用的bean触发初始化后回调...
   for (String beanName : beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
         final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
            smartSingleton.afterSingletonsInstantiated();
         }
      }
   }
}

3、进入 AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory 中的 

getBean方法
@Override
public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);//继续进入,进入最最核心方法
}
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
      @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

   final String beanName = transformedBeanName(name);
   System.out.println("====beanName=="+beanName+"===instance begin====");
   Object bean;

      //首先从缓存中拿实例
   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 + "'");
         }
      }
      //该方法是FactoryBean接口的调用入口
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }
   else {
      //如果singletonObjects缓存里面没有,则往下看
      //如果是scope 是Prototype的,校验是否有出现循环依赖,如果有则直接报错
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }

      // 检查这个工厂中是否存在bean定义
      BeanFactory parentBeanFactory = getParentBeanFactory();
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         //如果没有,则效验父类
         String nameToLookup = originalBeanName(name);
         if (parentBeanFactory instanceof AbstractBeanFactory) {
            return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                  nameToLookup, requiredType, args, typeCheckOnly);
         }
         else if (args != null) {
            // 使用显式参数委托给父进程
            return (T) parentBeanFactory.getBean(nameToLookup, args);
         }
         else if (requiredType != null) {
            // 没有参数 -> 委托给标准的getBean方法
            return parentBeanFactory.getBean(nameToLookup, requiredType);
         }
         else {
            return (T) parentBeanFactory.getBean(nameToLookup);
         }
      }
      if (!typeCheckOnly) {
         markBeanAsCreated(beanName);
      }
      try {
         //父子BeanDefinition合并
         final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         checkMergedBeanDefinition(mbd, beanName, args);
         //获取依赖对象属性,依赖对象要先实例化,即保证当前bean所依赖的bean先初始化。
         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 (mbd.isSingleton()) {//这里采用java8 lambda 表达式,函数式接口,取代以前的匿名内部类。
            sharedInstance = getSingleton(beanName, () -> {
               try {
                  return createBean(beanName, mbd, args);//ctrl+t 点击进入
               }
               catch (BeansException ex) {
                  //从单例缓存中显式删除实例:它可能已经被放在那里了
                 //先被创建进程,以允许循环引用解析。
                 //还要删除接收到该bean的临时引用的所有  bean对象。
                  destroySingleton(beanName);
                  throw ex;
               }
            });
            //改方法是FactoryBean接口的调用入口
            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);
            }
            //改方法是FactoryBean接口的调用入口
            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);
                  }
               });
               //改方法是FactoryBean接口的调用入口
               bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
            }
            catch (IllegalStateException ex) {
               throw new BeanCreationException(beanName,
                     "Scope '" + scopeName + "' is not active for the current thread; consider " +
                     "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                     ex);
            }
         }
      }
      catch (BeansException ex) {
         cleanupAfterBeanCreationFailure(beanName);
         throw ex;
      }
   }
   // 检查所需的类型是否与实际bean实例的类型相匹配
   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;
}

5、进入 AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory

@Override
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;
  
   //确保此时bean类已经解析,并且在动态解析类的情况下,克隆bean定义,不能共享的合并到bean中。
   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 {
      /*
      * TargetSource接口的运用,可以在用改一个类实现该接口,然后在里面定义实例化对象的方式,然后返回
      * 也就是说不需要spring帮助我们实例化对象,这里可以直接返回实例本身
      * 给beanpostprocessor一个机会来返回代理而不是目标bean实例, 这个代码简单看看,实际开发过程中很少用到。
      * */
      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,这个方法里面有多个主要分支,我们一一揭晓。

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

   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);//先从缓存中删除
   }
   if (instanceWrapper == null) {
      //创建实例后包装到BeanWrapper 中,这里就是bean的实例化过程,重点看,点击进入
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   final Object bean = instanceWrapper.getWrappedInstance();//再获取到这个对象
   Class<?> beanType = instanceWrapper.getWrappedClass();
   if (beanType != NullBean.class) {
      mbd.resolvedTargetType = beanType;
   }

   // 允许后置处理器修改合并bean
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            //CommonAnnotationBeanPostProcessor  支持了@PostConstruct,@PreDestroy,@Resource注解
            //AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解
            //BeanPostProcessor接口的典型运用,这里要着重理解这个接口
            //对类中注解的自动装配过程,这里是非常重要的一个分支 ,点击进入
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Post-processing of merged bean definition failed", ex);
         }
         mbd.postProcessed = true;
      }
   }

   //立刻缓存单例以便能够解析循环引用
   //甚至当由生命周期接口(如BeanFactoryAware)触发时也是如此。
   //单例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");
      }
      //这里着重理解,对理解循环依赖帮助非常大, 添加三级缓存,对象提前暴露,很重要,后面会讲,
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   Object exposedObject = bean;
   try {
      //ioc di,依赖注入的核心方法,点击进入
      populateBean(beanName, mbd, instanceWrapper);
      //bean 实例化+ioc依赖注入完以后的调用,非常重要
      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 {
      //注册bean销毁时的类DisposableBeanAdapter
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
   }

   return exposedObject;
}
点击 instanceWrapper = createBeanInstance(beanName, mbd, args);来到--->
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);
   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);
   }

   //如果有FactoryMethodName属性
   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?
   //寻找当前正在实例化的bean中有@Autowired注解的构造函数
   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
   if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      //如果ctors不为空,就说明构造函数上有@Autowired注解
      return autowireConstructor(beanName, mbd, ctors, args);
   }

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

   //无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化,里面通过反射获取构造器,然后实例化对象,最后包装到  // //beanWarpper 中返回,对象实例化结束,以后这个分支方法还会细讲,感兴趣的小伙伴,可以先提前预习。
   return instantiateBean(beanName, mbd);
}

点击 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 来到-->

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {  //获取所有的beanPostProcessors 接口类型的对象,循环遍历;判断是否是MergedBeanDefinitionPostProcessor 类型的;
//如果是就循环调用 postProcessMergedBeanDefinition 方法,该方法是对有 @Autowired、@Value、@PostConstruct、@PreDestroy、@Resource等常用注解的方法或属性进行收集装配并封装成对象。
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof MergedBeanDefinitionPostProcessor) {
         MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
         bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);//ctrl+t 如图显示-->
      }
   }
}

这里最主要涉及到  CommonAnnotationBeanPostProcessor 和AutowiredAnnotationBeanPostProcessor 类,

前者 CommonAnnotationBeanPostProcessor完成了@Resource @PostConstruct 和@PreDestory注解的属性或 者方法的收集和 支持。后者AutowiredAnnotationBeanPostProcessor 类,对@Autowired @Value注解的属性和方法的收集。收集过程基本上跟@Resource 注解的收集差不多。这里主要举例分析CommonAnnotationBeanPostProcessor 点击进入

6、来到 CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable  类中

/*
* 1、扫描类里面的属性或者方法
* 2、判断属性或者方法上面是否有@PostConstruct @PreDestroy @Resource注解
* 3、如果有注解的属性或者方法,包装成一个类
* */
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {

   //扫描@PostConstruct @PreDestroy
   super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
   //扫描@Resource,扫描属性和方法上面是否有@Resource注解,如果有则收集起来封装成对象,以后细讲。
   InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
   metadata.checkConfigMembers(beanDefinition);
}

另外 看一下构造方法,一眼就看到对@PostConstruct @PreDestroy注解的支持

public CommonAnnotationBeanPostProcessor() {
   setOrder(Ordered.LOWEST_PRECEDENCE - 3);
   setInitAnnotationType(PostConstruct.class);
   setDestroyAnnotationType(PreDestroy.class);
   ignoreResourceType("javax.xml.ws.WebServiceContext");
}

7、点 populateBean(beanName, mbd, instanceWrapper);来到-->

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

   if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }
      // Add property values based on autowire by type if applicable.
      if (mbd.getResolvedAutowireMode() == 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代码块,重要程度 5
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            //依赖注入核心过程,@Autowired的支持,ctrl+t 进入
            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               if (filteredPds == null) {
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
               }

               //老版本这个完成依赖注入过程,@Autowired的支持
               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);
   }
}
8、ctrl+t 点击 ibp.postProcessProperties 来到AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
      implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware 
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
//先取到有autowird 的
   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
   try {
      metadata.inject(bean, beanName, pvs);//点击
   }
   catch (BeanCreationException ex) {
      throw ex;
   }
   catch (Throwable ex) {
      throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
   }
   return pvs;
}

9、来到 InjectionMetadata

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
   Collection<InjectedElement> checkedElements = this.checkedElements;
   Collection<InjectedElement> elementsToIterate =
         (checkedElements != null ? checkedElements : this.injectedElements);
   if (!elementsToIterate.isEmpty()) {
      for (InjectedElement element : elementsToIterate) {
         if (logger.isTraceEnabled()) {
            logger.trace("Processing injected element of bean '" + beanName + "': " + element);
         }
         if(element.isField) {
            Field field = (Field)element.member;
         }
         element.inject(target, beanName, pvs);//循环遍历,点击进入
      }
   }
}
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
      throws Throwable {

   if (this.isField) {
      Field field = (Field) this.member;
      ReflectionUtils.makeAccessible(field);
      field.set(target, getResourceToInject(target, requestingBeanName));//这里完成了依赖注入
   }
   else {
      if (checkPropertySkipping(pvs)) {
         return;
      }
      try {
         Method method = (Method) this.member;
         ReflectionUtils.makeAccessible(method);
         method.invoke(target, getResourceToInject(target, requestingBeanName));
      }
      catch (InvocationTargetException ex) {
         throw ex.getTargetException();
      }
   }
}

时间关系今天写到这里,方法主干已经写完,下一篇开始分析相关分支方法,比如循环依赖注入、AOP入口、IOC之后的一些方法调用、bean的销毁等等,敬请期待。大家有不懂地方可以留言!

猜你喜欢

转载自blog.csdn.net/nandao158/article/details/105599086