头图

Bean loading (5)

The previous article mainly explained the createBeanInstance method and the instantiation process in creating beans. This article continues to explain about property injection and registration of DisposableBean during bean loading.

Property injection populateBean

After understanding circular dependencies, let's continue to see how property filling is implemented.

 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 {
                //没有可填充的属性
                return;
            }
        }

        //给InstantiationAwareBeanPostProcessors最后一个机会在属性设置前改变bean
        // 具体通过调用ibp.postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回
        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)) {
                        //返回值为是否继续填充bean
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }
        //如果后处理器发出停止填充命令则终止后续的执行
        if (!continueWithPropertyPopulation) {
            return;
        }

        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
        // 根据bean的依赖注入方式:即是否标注有 @Autowired 注解或 autowire=“byType/byName” 的标签
        // 会遍历bean中的属性,根据类型或名称来完成相应的注入
        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            //根据名称自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                // 代码(1)
                autowireByName(beanName, mbd, bw, newPvs);
            }
            //根据类型自动注入
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                // 代码(2)
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }
        // 容器是否注册了InstantiationAwareBeanPostProcessor
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        // 是否进行依赖检查
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                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;
                }
            }
        }
        // 检查是否满足相关依赖关系,对应的depends-on属性,3.0后已弃用
        if (needsDepCheck) {
            if (filteredPds == null) {
                filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
        // 如果pvs不为空,将pvs上所有的属性填充到BeanWrapper对应的Bean实例中
        if (pvs != null) {
      //代码(3)
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
}

The processing flow in the populateBean method is roughly as follows:

  1. The application of the postProcessAfterInstantiation method in the InstantiationAwareBeanPostProcessor processor can control whether the program continues to perform attribute filling
  2. According to the injection type (byType/byName), the dependent beans are extracted and stored in PropertyValues uniformly
  3. Apply the postProcessPropertyValues method of the InstantiationAwareBeanPostProcessor processor to process the properties again before the properties are filled and filled. The typical application is the verification of properties in the RequiredAnnotationBeanPostProcessor class.
  4. Fill all properties in PropertyValues into BeanWrapper

Let's first analyze the code (1) to see how byName is implemented.

autowireByName

 protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
   //寻找bw中需要依赖注入的属性
   String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
   for (String propertyName : propertyNames) {
      //检查缓存bean中是否存在当前bean
      if (containsBean(propertyName)) {
         //递归初始化相关的bean. 代码(1)
         Object bean = getBean(propertyName);
         pvs.add(propertyName, bean);
         //注册依赖
         registerDependentBean(propertyName, beanName);
         if (logger.isTraceEnabled()) {
            logger.trace("Added autowiring by name from bean name '" + beanName +
                  "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
         }
      } else {
         // 找不到则不处理
         if (logger.isTraceEnabled()) {
            logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                  "' by name: no matching bean found");
         }
      }
   }
}

The processing logic of byName is very simple, get the bean to be injected, and then recursively call getBean get bean for injection.

autowireByType

 protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
   // 获取自定义的类型转换器
   TypeConverter converter = getCustomTypeConverter();
   if (converter == null) {
      converter = bw;
   }

   Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
   //寻找bw中需要依赖注入的属性
   String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
   for (String propertyName : propertyNames) {
      try {
         // 获取属性描述符
         PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
         //不要尝试按类型为Object类型自动装配:即使从技术上讲是不满意的,非简单的属性,也没有意义。
         if (Object.class != pd.getPropertyType()) {
            //探测指定属性的set方法
            MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
            // Do not allow eager init for type matching in case of a prioritized post-processor.
            boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
            DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
            //解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中,当属性存在多个封装bean时
            //比如: @Autowired private List<A> aList; 就会找到所有匹配A类型的bean并将其注入
            Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
            if (autowiredArgument != null) {
               // 添加到待注入的bean列表中
               pvs.add(propertyName, autowiredArgument);
            }
            for (String autowiredBeanName : autowiredBeanNames) {
               //注册依赖
               registerDependentBean(autowiredBeanName, beanName);
               if (logger.isTraceEnabled()) {
                  logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
                        propertyName + "' to bean named '" + autowiredBeanName + "'");
               }
            }
            autowiredBeanNames.clear();
         }
      } catch (BeansException ex) {
         throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
      }
   }
}
  • Get type converter, if none, default to bw
  • Get the properties that need to be injected
  • Traverse all properties and start injection, first exclude the Object.class type, call the resolveDependency() method to verify and obtain the corresponding bean
  • Put it into pvs, and call the registerDependentBean() method to register the corresponding dependencies and dependencies

The autowiredBeanNames attribute mainly deals with the injection method of collection types, such as @autowired private List<A> tests , if it is a non-collection type, this attribute is useless.

Let's look at how the focus is on finding type matches. Enter the resolveDependency method.

DefaultListableBeanFactory#resolveDependency

 public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
      @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

   descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
   if (Optional.class == descriptor.getDependencyType()) {
      //Optional类注入的特殊处理
      return createOptionalDependency(descriptor, requestingBeanName);
   }
   else if (ObjectFactory.class == descriptor.getDependencyType() ||
         ObjectProvider.class == descriptor.getDependencyType()) {
      //ObjectFactory/ObjectProvider类注入的特殊处理
      return new DependencyObjectProvider(descriptor, requestingBeanName);
   }
   else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
      //javaxInjectProviderClass类注入的特殊处理
      return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
   }
   else {
      Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
            descriptor, requestingBeanName);
      if (result == null) {
         //通用处理逻辑
         result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
      }
      return result;
   }
}
 public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
      @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

   InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
   try {
      Object shortcut = descriptor.resolveShortcut(this);
      if (shortcut != null) {
         return shortcut;
      }
      //从descriptor中获取属性类型
      Class<?> type = descriptor.getDependencyType();
      //用于支持注解@Value
      Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
      if (value != null) {
         if (value instanceof String) {
            String strVal = resolveEmbeddedValue((String) value);
            BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                  getMergedBeanDefinition(beanName) : null);
            value = evaluateBeanDefinitionString(strVal, bd);
         }
         TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
         try {
            return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
         }
         catch (UnsupportedOperationException ex) {
            // A custom TypeConverter which does not support TypeDescriptor resolution...
            return (descriptor.getField() != null ?
                  converter.convertIfNecessary(value, type, descriptor.getField()) :
                  converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
         }
      }

      Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
      if (multipleBeans != null) {
         return multipleBeans;
      }
      //查找符合注入属性类型的bean ,这里过滤了 @Bean(autowireCandidate = false)和不符合@Qualifier("beanName")的bean
      Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
      if (matchingBeans.isEmpty()) {
         //为空说明找不到该注入类型的bean,如果注入的属性又是必须的,则抛出异常NoSuchBeanDefinitionException
         if (isRequired(descriptor)) {
            raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
         }
         return null;
      }

      String autowiredBeanName;
      Object instanceCandidate;
      //查询到多个符合注入属性类型的bean
      if (matchingBeans.size() > 1) {
         // 再次过滤找到最优的beanName,进而获取最优的用来创建实例的候选者instanceCandidate
         // 这里挑选@primary、@Priority等优先级高的bean
         autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
         if (autowiredBeanName == null) {
            // 找不到最优的beanName,注入的属性又是必须的,则抛NoUniqueBeanDefinitionException异常
            // 注入的属性非必须,未过滤前就有多个注入属性类型的bean,如果注入的属性不是集合,也抛异常
            if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
               return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
            }
            else {
               return null;
            }
         }
         // 根据beanName获取最优的用来创建属性实例的候选者instanceCandidate
         instanceCandidate = matchingBeans.get(autowiredBeanName);
      }
      else {
         //确定只有一个匹配项
         Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
         autowiredBeanName = entry.getKey();
         instanceCandidate = entry.getValue();
      }

      if (autowiredBeanNames != null) {
         autowiredBeanNames.add(autowiredBeanName);
      }
      if (instanceCandidate instanceof Class) {
         instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
      }
      Object result = instanceCandidate;
      if (result instanceof NullBean) {
         if (isRequired(descriptor)) {
            raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
         }
         result = null;
      }
      if (!ClassUtils.isAssignableValue(type, result)) {
         throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
      }
      return result;
   }
   finally {
      ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
   }
}

When looking for the matching execution order of types, this method first tries to use the parser for parsing. If the parsing fails, it may be that the default parser is used without any processing, or a custom parser is used, but for types such as collections It is not within the scope of parsing, so again different types are handled differently.

applyPropertyValues

After executing this, the acquisition of all injected properties has been completed, but the acquired properties are in the form of PropertyValues and have not been applied to the instantiated bean. This work is done in 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());
   }

   MutablePropertyValues mpvs = null;
   List<PropertyValue> original;

   if (pvs instanceof MutablePropertyValues) {
      mpvs = (MutablePropertyValues) pvs;
      //如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanWrapper
      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);
         }
      }
      original = mpvs.getPropertyValueList();
   } else {
      //如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
      original = Arrays.asList(pvs.getPropertyValues());
   }

   TypeConverter converter = getCustomTypeConverter();
   if (converter == null) {
      converter = bw;
   }
   //获取对应的解析器
   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;
   //遍历属性,将属性转换为对应属性的类型
   for (PropertyValue pv : original) {
      if (pv.isConverted()) {
         deepCopy.add(pv);
      } else {
         String propertyName = pv.getName();
         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);
         }
         Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
         Object convertedValue = resolvedValue;
         boolean convertible = bw.isWritableProperty(propertyName) &&
               !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
         if (convertible) {
            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))) {
            pv.setConvertedValue(convertedValue);
            deepCopy.add(pv);
         } else {
            resolveNecessary = true;
            deepCopy.add(new PropertyValue(pv, convertedValue));
         }
      }
   }
   if (mpvs != null && !resolveNecessary) {
      mpvs.setConverted();
   }

   // Set our (possibly massaged) deep copy.
   try {
      bw.setPropertyValues(new MutablePropertyValues(deepCopy));
   } catch (BeansException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Error setting property values", ex);
   }
}

initialize beans

We know that there is an attribute init-method when configuring a bean. This attribute is to call the specified method before the bean is instantiated, and instantiate it according to the business requirements. We still return to doCreateBean now.

initializeBean

 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         //代码(1)  激活 Aware 方法
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   } else {
      //对特殊的bean处理,Aware / BeanClassLoaderAware / BeanFactoryAware
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      // 调用bean后处理器的方法
      // BeanPostProcessor 提供的方法,在bean初始化前调用,这时的 bean已完成了实例化和属性填充注入工作
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      //激活用户自定义的init方法
      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()) {
      // 调用bean后处理器的方法
      // BeanPostProcessor 提供的方法,在bean初始化后调用,这时候的bean 已经创建完成了
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }
   return wrappedBean;
}

Although the main purpose of this method is to perform the invocation of the initialization method we set up, there are other necessary tasks in addition to this.

1.激活Aware方法

Before understanding the principle, let's first understand what is Aware, Spring

Some Aware-related interfaces are provided, such as BeanFactoryAware, ApplicationContextAware, ResourceLoaderAware, ServletContextAware, etc. For example, after the bean that implements the BeanFactoryAware interface is initialized, the Spring container will inject an instance of BeanFactory, and the bean that implements the ApplicationContextAware interface will be injected into the ApplicationContext. examples, etc.

Let's first look at the use of Aware.

  1. define a plain bean
 /**
 * @author 神秘杰克
 * 公众号: Java菜鸟程序员
 * @date 2022/6/8
 * @Description
 */
public class Hello {

   public void say(){
      System.out.println("hello");
   }

}
  1. Define a bean of type BeanFactoryAware
 /**
 * @author 神秘杰克
 * 公众号: Java菜鸟程序员
 * @date 2022/6/8
 * @Description
 */
public class AwareTest implements BeanFactoryAware {

   private BeanFactory beanFactory;

   //声明bean的时候Spring会自动注入BeanFactory
   @Override
   public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
      this.beanFactory = beanFactory;
   }

   public void testAware(){
      //通过beanFactory获取hello bean
      final Hello hello = (Hello) beanFactory.getBean("hello");
      hello.say();
   }

}
  1. register bean
 <bean id="hello" class="cn.jack.Hello"/>

<bean id="awareTest" class="cn.jack.AwareTest"/>
  1. test
 public class Test {

   public static void main(String[] args) {
      final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
      final AwareTest awareTest = (AwareTest) applicationContext.getBean("awareTest");
      awareTest.testAware();

   }
}
  1. Results of the
 hello

According to the above method, we can get the BeanFactory in Spring, and can get all the beans according to the BeanFactory, and make related settings. Other Awares are similar.

Specifically, let's take a look at the method called by code (1) to see it clearly. very simple.

 private void invokeAwareMethods(final String beanName, final Object bean) {
   if (bean instanceof Aware) {
      if (bean instanceof BeanNameAware) {
         ((BeanNameAware) bean).setBeanName(beanName);
      }
      if (bean instanceof BeanClassLoaderAware) {
         ClassLoader bcl = getBeanClassLoader();
         if (bcl != null) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
         }
      }
      if (bean instanceof BeanFactoryAware) {
         ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
      }
   }
}

2. 处理器的应用

BeanPostProcessor is an indispensable bright spot in the open architecture of Spring. It gives users sufficient permissions to change or extend Spring. In addition to BeanPostProcessor, there are many other PostProcessors. Of course, most of them are based on this and inherit from BeanPostProcessor. .

Before and after calling our custom initialization method, the postProcessBeforeInitialization and postProcessAfterInitialization methods of BeanPostProcessor will be called respectively, so that we can process the response according to business needs.

 public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   // 获取所有实现了 BeanPostProcessors 接口的类,进行遍历
   for (BeanPostProcessor processor : getBeanPostProcessors()) {
      // 核心方法:postProcessBeforeInitialization
      Object current = processor.postProcessBeforeInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}
 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
    // 获取所有实现了 BeanPostProcessors 接口的类,进行遍历
   for (BeanPostProcessor processor : getBeanPostProcessors()) {
     // 核心方法:postProcessAfterInitialization
      Object current = processor.postProcessAfterInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

3. 激活自定义的init方法

In addition to using the init-method for the initialization method, there are also custom beans that implement the InitializingBean interface and implement the afterPropertiesSet method to implement their own initialization business logic.

Of course, these two are executed when the bean is initialized. The execution order is that afterPropertiesSet is executed first, and init-method is executed after.
 protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
      throws Throwable {

   //先检查是否为isInitializingBean,如果是的话先调用afterPropertiesSet方法
   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      if (logger.isTraceEnabled()) {
         logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      }
      // 调用 afterPropertiesSet  方法
      if (System.getSecurityManager() != null) {
         try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
               ((InitializingBean) bean).afterPropertiesSet();
               return null;
            }, getAccessControlContext());
         } catch (PrivilegedActionException pae) {
            throw pae.getException();
         }
      } else {
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }

   if (mbd != null && bean.getClass() != NullBean.class) {
      // 从RootBeanDefinition 中获取initMethod 方法名称
      String initMethodName = mbd.getInitMethodName();
      if (StringUtils.hasLength(initMethodName) &&
            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
         // 调用initMethod 方法
         invokeCustomInitMethod(beanName, bean, mbd);
      }
   }
}

It should be noted that when using the @PostConstruct annotation and implementing the InitializingBean interface and init-method.

The execution order is PostConstruct -> InitializingBean -> init-method

Register DisposableBean

There is a final step in doCreateBean, which is to register the bean to disposableBeans, so that the specified related business can be run when the bean is destroyed.

In addition to the well-known destroy-method method, we can also register a post-processor DestructionAwareBeanPostProcessor to unify the bean's destruction method.

 protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
   AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
   if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
      //如果为单例
      if (mbd.isSingleton()) {
         /**
          * 注册一个DisposableBean的实现为以下三种给出的bean做所有的销毁工作:
          *     DestructionAwareBeanPostProcessor,DisposableBean,自定义destroy方法
          */
         registerDisposableBean(beanName,
               new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      }
      else {
         //自定义scope的处理
         Scope scope = this.scopes.get(mbd.getScope());
         if (scope == null) {
            throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
         }
         scope.registerDestructionCallback(beanName,
               new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      }
   }
}

At this point, the loading process of Spring beans comes to an end.


神秘杰克
765 声望383 粉丝

Be a good developer.