暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Spring源码分析之容器初始化(3)

徘徊笔记 2019-07-09
121


创建单例bean

    // Create bean instance.
    if (mbd.isSingleton()) {
    sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
    @Override
    public Object getObject() throws BeansException {
    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);
    }


    查看单例实例缓存,检查单例创建状态,执行前置方法添加正在创建实例的bean名字,执行单例工厂回调方法获取bean实例,执行后置方法移除正在创建实例bean名字

      public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
      Assert.notNull(beanName, "'beanName' must not be null");
      synchronized (this.singletonObjects) {
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
      if (this.singletonsCurrentlyInDestruction) {
      throw new BeanCreationNotAllowedException(beanName,
      "Singleton bean creation not allowed while the 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 + "'");
      }
      beforeSingletonCreation(beanName);
      boolean newSingleton = false;
      boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
      if (recordSuppressedExceptions) {
      this.suppressedExceptions = new LinkedHashSet<Exception>();
      }
      try {
      singletonObject = singletonFactory.getObject();
      newSingleton = true;
            }
      finally {
      if (recordSuppressedExceptions) {
      this.suppressedExceptions = null;
      }
      afterSingletonCreation(beanName);
      }
      if (newSingleton) {
      addSingleton(beanName, singletonObject);
      }
      }
      return (singletonObject != NULL_OBJECT ? singletonObject : null);
      }
      }


      把实例添加到单例集合中,并移除早期存储的bean名字

        protected void addSingleton(String beanName, Object singletonObject) {
        synchronized (this.singletonObjects) {
        this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        this.registeredSingletons.add(beanName);
        }
        }


        解析正确的bean类型,如果bean定义没有类型的话就重新设置

          protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException
          Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
          if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
          mbdToUse = new RootBeanDefinition(mbd);
          mbdToUse.setBeanClass(resolvedClass);
          }


          准备计算方法是否覆盖

            mbdToUse.prepareMethodOverrides();


            public void prepareMethodOverrides() throws BeanDefinitionValidationException {
            Check that lookup methods exists.
            MethodOverrides methodOverrides = getMethodOverrides();
            if (!methodOverrides.isEmpty()) {
            Set<MethodOverride> overrides = methodOverrides.getOverrides();
            synchronized (overrides) {
            for (MethodOverride mo : overrides) {
            prepareMethodOverride(mo);
            }
            }
            }
            }


            protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
            int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
            if (count == 0) {
            throw new BeanDefinitionValidationException(
            "Invalid method override: no method with name '" + mo.getMethodName() +
            "' on class [" + getBeanClassName() + "]");
            }
            else if (count == 1) {
            Mark override as not overloaded, to avoid the overhead of arg type checking.
            mo.setOverloaded(false);
            }
            }


            实例化前解析是否直接有代理返回,具体执行方法在接口InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法

              Object bean = resolveBeforeInstantiation(beanName, mbdToUse);


              protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
              Object bean = null;
              if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
              // Make sure bean class is actually resolved at this point.
              if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
              Class<?> targetType = determineTargetType(beanName, mbd);
              if (targetType != null) {
              bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
              if (bean != null) {
              bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
              }
              }
              }
              mbd.beforeInstantiationResolved = (bean != null);
              }
              return bean;
                }


              没有代理类的话就创建bean

                Object beanInstance = doCreateBean(beanName, mbdToUse, args);


                // Instantiate the bean.
                BeanWrapper instanceWrapper = null;
                if (mbd.isSingleton()) {
                instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
                }
                if (instanceWrapper == null) {
                instanceWrapper = createBeanInstance(beanName, mbd, args);
                }


                实例化bean

                  protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
                  // Make sure bean class is actually resolved at this point.
                  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());
                  }


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


                  // Need to determine the constructor...
                  Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
                  if (ctors != null ||
                  mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
                  mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
                  return autowireConstructor(beanName, mbd, ctors, args);
                  }


                  // No special handling: simply use no-arg constructor.
                  return instantiateBean(beanName, mbd);
                  }


                  从bean处理器中决定选择哪个构造器,通过调用接口SmartInstantiationAwareBeanPostProcessor的determineCandidateConstructors方法来选择,如果有选择出来的构造器或者bean注入类型是构造器注入或者bean定义有构造器参数值或者传参不为空的话,就采用构造器注入方式,否则进行无参构造器实例化,如果有覆盖方法的话,就使用CGLIB覆盖类。

                    protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
                    throws BeansException {


                    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
                    for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                    if (ctors != null) {
                    return ctors;
                    }
                    }
                    }
                    }
                    return null;
                    }


                    获取bean类型,判断bean定义是否已经被后处理

                      final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
                      Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
                      // Allow post-processors to modify the merged bean definition.
                      synchronized (mbd.postProcessingLock) {
                      if (!mbd.postProcessed) {
                      applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                      mbd.postProcessed = true;
                      }
                      }


                      依次执行接口MergedBeanDefinitionPostProcessor的合并定义方法postProcessMergedBeanDefinition

                        protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
                        throws BeansException {


                        try {
                        for (BeanPostProcessor bp : getBeanPostProcessors()) {
                        if (bp instanceof MergedBeanDefinitionPostProcessor) {
                        MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                        bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
                        }
                        }
                        }
                        catch (Exception ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing failed of bean type [" + beanType + "] failed", ex);
                        }
                        }


                        暴露早期单例,即使在像BeanFactoryAware这样的生命周期接口触发时,也急切地缓存单例以便能够解析循环引用。

                          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");
                          }
                          addSingletonFactory(beanName, new ObjectFactory<Object>() {
                          @Override
                          public Object getObject() throws BeansException {
                          return getEarlyBeanReference(beanName, mbd, bean);
                          }
                          });
                          }


                          当单例对象不存在时添加单例工厂,移除早期单例,添加注册单例

                            protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
                            Assert.notNull(singletonFactory, "Singleton factory must not be null");
                            synchronized (this.singletonObjects) {
                            if (!this.singletonObjects.containsKey(beanName)) {
                            this.singletonFactories.put(beanName, singletonFactory);
                            this.earlySingletonObjects.remove(beanName);
                            this.registeredSingletons.add(beanName);
                            }
                            }
                            }

                            文章转载自徘徊笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                            评论