<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      Spring之BeanFactory:解析getBean()方法

      初探getBean()方法

      在使用Spring的時候,可以通過如下方式調用getBean方法來獲取某個Bean:

      User user =  context.getBean(User.class);

       

      AbstractApplicationContext中定義了一系列getBean方法,代碼如下:

          //---------------------------------------------------------------------
          // Implementation of BeanFactory interface
          //---------------------------------------------------------------------
      
          @Override
          public Object getBean(String name) throws BeansException {
              assertBeanFactoryActive();
              return getBeanFactory().getBean(name);
          }
      
          @Override
          public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
              assertBeanFactoryActive();
              return getBeanFactory().getBean(name, requiredType);
          }
      
          @Override
          public Object getBean(String name, Object... args) throws BeansException {
              assertBeanFactoryActive();
              return getBeanFactory().getBean(name, args);
          }
      
          @Override
          public <T> T getBean(Class<T> requiredType) throws BeansException {
              assertBeanFactoryActive();
              return getBeanFactory().getBean(requiredType);
          }
      
          @Override
          public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
              assertBeanFactoryActive();
              return getBeanFactory().getBean(requiredType, args);
          }

      解讀:

      上述getBean方法本質上是通過BeanFactory的getBean方法來實現的。 

       

      Note:

      AbstractApplicationContext中getBeanFactory為抽象方法,代碼如下:

          /**
           * Subclasses must return their internal bean factory here. They should implement the
           * lookup efficiently, so that it can be called repeatedly without a performance penalty.
           * <p>Note: Subclasses should check whether the context is still active before
           * returning the internal bean factory. The internal factory should generally be
           * considered unavailable once the context has been closed.
           * @return this application context's internal bean factory (never {@code null})
           * @throws IllegalStateException if the context does not hold an internal bean factory yet
           * (usually if {@link #refresh()} has never been called) or if the context has been
           * closed already
           * @see #refreshBeanFactory()
           * @see #closeBeanFactory()
           */
          @Override
          public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

      解讀:

      此方法的具體邏輯由子類實現。

      Note:

      此方法的返回值類型是ConfigurableListableBeanFactory。

      BeanFactory類圖

      下圖為BeanFactory相關類圖:

      BeanFactory接口

      BeanFactory接口是Spring容器的核心接口,負責:實例化、定位、配置應用程序中的對象及建立這些對象間的依賴。

      • HierarhicalBeanFactory

      該接口允許子容器訪問父容器,其中方法如下圖所示:

      • ConfigurableBeanFactory

      該接口增強了 IoC 容器的可定制性,它定義了設置類裝載器、屬性編輯器、容器初始化后置處理器等方法,下圖僅列出了其中部分方法:

       

      • AutowireCapableBeanFactory

      該接口定義了將容器中的 Bean 按某種規則(如:按名稱匹配、按類型匹配)進行自動裝配的方法,其中方法如下圖所示:

      • ListableBeanFactory

      該接口定義了訪問容器中 Bean 基本信息的若干方法,如:查看 Bean 的個數、獲取某一類型 Bean 的名稱,其中方法如下圖所示:

      • ConfigurableListableBeanFactory

      BeanFactory實現

      Spring提供了許多易用的BeanFactory實現,從前述類圖可以發現DefaultListableBeanFactory就是其中之一,如下:

       

       

      XmlBeanFactory是DefaultListableBeanFactory的子類,如下:

      public class XmlBeanFactory extends DefaultListableBeanFactory {
      
          private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
      
      
          /**
           * Create a new XmlBeanFactory with the given resource,
           * which must be parsable using DOM.
           * @param resource the XML resource to load bean definitions from
           * @throws BeansException in case of loading or parsing errors
           */
          public XmlBeanFactory(Resource resource) throws BeansException {
              this(resource, null);
          }
      
          /**
           * Create a new XmlBeanFactory with the given input stream,
           * which must be parsable using DOM.
           * @param resource the XML resource to load bean definitions from
           * @param parentBeanFactory parent bean factory
           * @throws BeansException in case of loading or parsing errors
           */
          public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
              super(parentBeanFactory);
              this.reader.loadBeanDefinitions(resource);
          }
      
      }

       

      深入getBean()方法

      BeanFactory接口中的方法如下圖所示:

      解讀:

      這幾個getBean方法由AbstractBeanFactory、DefaultListableBeanFactory實現

       

      (1)org.springframework.beans.factory.support.AbstractBeanFactory中getBean()方法的定義如下:

          //---------------------------------------------------------------------
          // Implementation of BeanFactory interface
          //---------------------------------------------------------------------
      
          @Override
          public Object getBean(String name) throws BeansException {
              return doGetBean(name, null, null, false);
          }
      
          @Override
          public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
              return doGetBean(name, requiredType, null, false);
          }
      
          @Override
          public Object getBean(String name, Object... args) throws BeansException {
              return doGetBean(name, null, args, false);
          }

       

      (2)org.springframework.beans.factory.support.DefaultListableBeanFactory中getBean()方法的定義如下:

          //---------------------------------------------------------------------
          // Implementation of remaining BeanFactory methods
          //---------------------------------------------------------------------
      
          @Override
          public <T> T getBean(Class<T> requiredType) throws BeansException {
              return getBean(requiredType, (Object[]) null);
          }
      
          @SuppressWarnings("unchecked")
          @Override
          public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException {
              Assert.notNull(requiredType, "Required type must not be null");
              Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
              if (resolved == null) {
                  throw new NoSuchBeanDefinitionException(requiredType);
              }
              return (T) resolved;
          }

       

      AbstractBeanFactory

      AbstractBeanFactory中的getBean方法均調用了doGetBean(...)方法,該方法的定義如下:

          /**
           * Return an instance, which may be shared or independent, of the specified bean.
           * @param name the name of the bean to retrieve
           * @param requiredType the required type of the bean to retrieve
           * @param args arguments to use when creating a bean instance using explicit arguments
           * (only applied when creating a new instance as opposed to retrieving an existing one)
           * @param typeCheckOnly whether the instance is obtained for a type check,
           * not for actual use
           * @return an instance of the bean
           * @throws BeansException if the bean could not be created
           */
          @SuppressWarnings("unchecked")
          protected <T> T doGetBean(
                  String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
                  throws BeansException {
      
              String beanName = transformedBeanName(name);
              Object beanInstance;
      
              // Eagerly check singleton cache for manually registered singletons.
              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 + "'");
                      }
                  }
                  beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
              }
      
              else {
                  // Fail if we're already creating this bean instance:
                  // We're assumably within a circular reference.
                  if (isPrototypeCurrentlyInCreation(beanName)) {
                      throw new BeanCurrentlyInCreationException(beanName);
                  }
      
                  // Check if bean definition exists in this factory.
                  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);
                      }
                  }
      
                  if (!typeCheckOnly) {
                      markBeanAsCreated(beanName);
                  }
      
                  StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
                          .tag("beanName", name);
                  try {
                      if (requiredType != null) {
                          beanCreation.tag("beanType", requiredType::toString);
                      }
                      RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                      checkMergedBeanDefinition(mbd, beanName, args);
      
                      // Guarantee initialization of beans that the current 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);
                              }
                          }
                      }
      
                      // Create bean instance.
                      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;
                              }
                          });
                          beanInstance = 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);
                          }
                          beanInstance = 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);
                                  }
                              });
                              beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                          }
                          catch (IllegalStateException ex) {
                              throw new ScopeNotActiveException(beanName, scopeName, ex);
                          }
                      }
                  }
                  catch (BeansException ex) {
                      beanCreation.tag("exception", ex.getClass().toString());
                      beanCreation.tag("message", String.valueOf(ex.getMessage()));
                      cleanupAfterBeanCreationFailure(beanName);
                      throw ex;
                  }
                  finally {
                      beanCreation.end();
                  }
              }
      
              return adaptBeanInstance(name, beanInstance, requiredType);
          }

      解讀:

      上述方法調用了createBean方法,對應的參數分別是beanName、mbd、args(建議重點關注一下mbd,RootBeanDefinition類型)。

      Note:

      Spring 配置文件中每一個 bean 節點元素在 Spring 容器里都由一個BeanDefinition 對象表示,它包含了某個 Bean 的具體信息。

       

      BeanDefinition相關類圖如下:

       

      createBean方法的定義如下:

          /**
           * Create a bean instance for the given merged bean definition (and arguments).
           * The bean definition will already have been merged with the parent definition
           * in case of a child definition.
           * <p>All bean retrieval methods delegate to this method for actual bean creation.
           * @param beanName the name of the bean
           * @param mbd the merged bean definition for the bean
           * @param args explicit arguments to use for constructor or factory method invocation
           * @return a new instance of the bean
           * @throws BeanCreationException if the bean could not be created
           */
          protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                  throws BeanCreationException;

      解讀:

      上述createBean方法為抽象方法,由子類實現。


      AbstractAutowireCapableBeanFactory —— createBean方法

      AbstractAutowireCapableBeanFactory中CreateBean方法

      /**
       * Central method of this class: creates a bean instance,
       * populates the bean instance, applies post-processors, etc.
       * @see #doCreateBean
       */
      @Override
      protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
          if (logger.isDebugEnabled()) {
              logger.debug("Creating instance of bean '" + beanName + "'");
          }
          RootBeanDefinition mbdToUse = mbd;
      
          // Make sure bean class is actually resolved at this point, and
          // clone the bean definition in case of a dynamically resolved Class
          // which cannot be stored in the shared merged bean definition.
          Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
          if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
              mbdToUse = new RootBeanDefinition(mbd);
              mbdToUse.setBeanClass(resolvedClass);
          }
      
          // Prepare method overrides.
          try {
              mbdToUse.prepareMethodOverrides();
          }
          catch (BeanDefinitionValidationException ex) {
              throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                      beanName, "Validation of method overrides failed", ex);
          }
      
          try {
              // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
              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);
          }
      
          Object beanInstance = doCreateBean(beanName, mbdToUse, args);
          if (logger.isDebugEnabled()) {
              logger.debug("Finished creating instance of bean '" + beanName + "'");
          }
          return beanInstance;
      }

      解讀:

      (1)resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd)

          /**
           * Apply before-instantiation post-processors, resolving whether there is a
           * before-instantiation shortcut for the specified bean.
           * @param beanName the name of the bean
           * @param mbd the bean definition for the bean
           * @return the shortcut-determined bean instance, or {@code null} if none
           */
          @Nullable
          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;
          }

       

      (2)一般情況下,某個類型的Bean是由doCreateBean方法實現的,對應代碼如下:

      /**
       * Actually create the specified bean. Pre-creation processing has already happened
       * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
       * <p>Differentiates between default bean instantiation, use of a
       * factory method, and autowiring a constructor.
       * @param beanName the name of the bean
       * @param mbd the merged bean definition for the bean
       * @param args explicit arguments to use for constructor or factory method invocation
       * @return a new instance of the bean
       * @throws BeanCreationException if the bean could not be created
       * @see #instantiateBean
       * @see #instantiateUsingFactoryMethod
       * @see #autowireConstructor
       */
      protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
          // Instantiate the bean.
          BeanWrapper instanceWrapper = null;
          if (mbd.isSingleton()) {
              instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
          }
          if (instanceWrapper == null) {
              instanceWrapper = createBeanInstance(beanName, mbd, args);
          }
          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;
              }
          }
      
          // 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.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);
                  }
              });
          }
      
          // Initialize the bean instance.
          Object exposedObject = bean;
          try {
              populateBean(beanName, mbd, instanceWrapper);
              if (exposedObject != null) {
                  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<String>(dependentBeans.length);
                      for (String dependentBean : dependentBeans) {
                          if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                              actualDependentBeans.add(dependentBean);
                          }
                      }
                      if (!actualDependentBeans.isEmpty()) {
                          throw new BeanCurrentlyInCreationException(beanName,
                                  "Bean with name '" + beanName + "' has been injected into other beans [" +
                                  StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                  "] in its raw version as part of a circular reference, but has eventually been " +
                                  "wrapped. This means that said other beans do not use the final version of the " +
                                  "bean. This is often the result of over-eager type matching - consider using " +
                                  "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                      }
                  }
              }
          }
      
          // Register bean as disposable.
          try {
              registerDisposableBeanIfNecessary(beanName, bean, mbd);
          }
          catch (BeanDefinitionValidationException ex) {
              throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
          }
      
          return exposedObject;
      }

       

          /**
           * Create a new instance for the specified bean, using an appropriate instantiation strategy:
           * factory method, constructor autowiring, or simple instantiation.
           * @param beanName the name of the bean
           * @param mbd the bean definition for the bean
           * @param args explicit arguments to use for constructor or factory method invocation
           * @return a BeanWrapper for the new instance
           * @see #obtainFromSupplier
           * @see #instantiateUsingFactoryMethod
           * @see #autowireConstructor
           * @see #instantiateBean
           */
          protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable 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());
              }
      
              Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
              if (instanceSupplier != null) {
                  return obtainFromSupplier(instanceSupplier, beanName);
              }
      
              if (mbd.getFactoryMethodName() != null) {
                  return instantiateUsingFactoryMethod(beanName, mbd, args);
              }
      
              // Shortcut when re-creating the same bean...
              boolean resolved = false;
              boolean autowireNecessary = false;
              if (args == null) {
                  synchronized (mbd.constructorArgumentLock) {
                      if (mbd.resolvedConstructorOrFactoryMethod != null) {
                          resolved = true;
                          autowireNecessary = mbd.constructorArgumentsResolved;
                      }
                  }
              }
              if (resolved) {
                  if (autowireNecessary) {
                      return autowireConstructor(beanName, mbd, null, null);
                  }
                  else {
                      return instantiateBean(beanName, mbd);
                  }
              }
      
              // Candidate constructors for autowiring?
              Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
              if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                      mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
                  return autowireConstructor(beanName, mbd, ctors, args);
              }
      
              // Preferred constructors for default construction?
              ctors = mbd.getPreferredConstructors();
              if (ctors != null) {
                  return autowireConstructor(beanName, mbd, ctors, null);
              }
      
              // No special handling: simply use no-arg constructor.
              return instantiateBean(beanName, mbd);
          }

       

          /**
           * Populate the bean instance in the given BeanWrapper with the property values
           * from the bean definition.
           * @param beanName the name of the bean
           * @param mbd the bean definition for the bean
           * @param bw the BeanWrapper with bean instance
           */
          @SuppressWarnings("deprecation")  // for postProcessPropertyValues
          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 (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
                      if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                          return;
                      }
                  }
              }
      
              PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
      
              int resolvedAutowireMode = mbd.getResolvedAutowireMode();
              if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                  MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
                  // Add property values based on autowire by name if applicable.
                  if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                      autowireByName(beanName, mbd, bw, newPvs);
                  }
                  // Add property values based on autowire by type if applicable.
                  if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                      autowireByType(beanName, mbd, bw, newPvs);
                  }
                  pvs = newPvs;
              }
      
              boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
              boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
      
              PropertyDescriptor[] filteredPds = null;
              if (hasInstAwareBpps) {
                  if (pvs == null) {
                      pvs = mbd.getPropertyValues();
                  }
                  for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
                      PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                      if (pvsToUse == null) {
                          if (filteredPds == null) {
                              filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                          }
                          pvsToUse = bp.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);
              }
          }

       

          /**
           * Initialize the given bean instance, applying factory callbacks
           * as well as init methods and bean post processors.
           * <p>Called from {@link #createBean} for traditionally defined beans,
           * and from {@link #initializeBean} for existing bean instances.
           * @param beanName the bean name in the factory (for debugging purposes)
           * @param bean the new bean instance we may need to initialize
           * @param mbd the bean definition that the bean was created with
           * (can also be {@code null}, if given an existing bean instance)
           * @return the initialized bean instance (potentially wrapped)
           * @see BeanNameAware
           * @see BeanClassLoaderAware
           * @see BeanFactoryAware
           * @see #applyBeanPostProcessorsBeforeInitialization
           * @see #invokeInitMethods
           * @see #applyBeanPostProcessorsAfterInitialization
           */
          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 {
                  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生命周期(即:實例化 -> 屬性賦值 -> 初始化 -> 銷毀)中的前三個階段

      posted @ 2021-09-04 16:57  時空穿越者  閱讀(3838)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 久久涩综合一区二区三区| 浑源县| 国产卡一卡二卡三免费入口| 亚洲欧美日韩成人综合一区| 中文字幕精品亚洲无线码二区| 日本一区二区三区在线 |观看| 亚洲乱码中文字幕小综合| 亚洲AV无码久久精品日韩| 国产成人永久免费av在线| 精品人妻伦一二三区久久aaa片| 国产在线无码不卡播放| 好男人官网资源在线观看| 久热re这里精品视频在线6| 无码中文av波多野结衣一区| av 日韩 人妻 黑人 综合 无码| 欧美白人最猛性xxxxx| 国产精品自拍中文字幕| 韩国深夜福利视频在线观看| аⅴ天堂国产最新版在线中文| 美女午夜福利视频一区二区| 国产精品成人午夜福利| 莱西市| 国产在线无码不卡播放| 女人高潮被爽到呻吟在线观看| 精品国产成人一区二区| 日韩av日韩av在线| 日韩中文字幕av有码| 久久99久国产麻精品66| 狠狠做五月深爱婷婷伊人| 精品人妻二区中文字幕| 亚洲天堂av免费在线看| 国产小受被做到哭咬床单GV| 国产精品入口中文字幕| 高潮精品熟妇一区二区三区| 国产一区二区三区内射高清| 国产精品老熟女露脸视频| 久久影院午夜伦手机不四虎卡 | 亚洲一区二区三区啪啪| 综合偷自拍亚洲乱中文字幕| 宜昌市| 人妻av中文字幕无码专区|