1. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  2. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  3. throws BeanCreationException {
  4. // Instantiate the bean.
  5. BeanWrapper instanceWrapper = null;
  6. if (mbd.isSingleton()) {
  7. // bean实例Wrapper 对象
  8. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  9. }
  10. if (instanceWrapper == null) {
  11. instanceWrapper = createBeanInstance(beanName, mbd, args);
  12. }
  13. Object bean = instanceWrapper.getWrappedInstance();
  14. Class<?> beanType = instanceWrapper.getWrappedClass();
  15. if (beanType != NullBean.class) {
  16. mbd.resolvedTargetType = beanType;
  17. }
  18. // Allow post-processors to modify the merged bean definition.
  19. synchronized (mbd.postProcessingLock) {
  20. if (!mbd.postProcessed) {
  21. try {
  22. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  26. "Post-processing of merged bean definition failed", ex);
  27. }
  28. mbd.postProcessed = true;
  29. }
  30. }
  31. // Eagerly cache singletons to be able to resolve circular references
  32. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  33. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  34. isSingletonCurrentlyInCreation(beanName));
  35. if (earlySingletonExposure) {
  36. if (logger.isTraceEnabled()) {
  37. logger.trace("Eagerly caching bean '" + beanName +
  38. "' to allow for resolving potential circular references");
  39. }
  40. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  41. }
  42. // Initialize the bean instance.
  43. Object exposedObject = bean;
  44. try {
  45. populateBean(beanName, mbd, instanceWrapper);
  46. exposedObject = initializeBean(beanName, exposedObject, mbd);
  47. }
  48. catch (Throwable ex) {
  49. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  50. throw (BeanCreationException) ex;
  51. }
  52. else {
  53. throw new BeanCreationException(
  54. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  55. }
  56. }
  57. if (earlySingletonExposure) {
  58. Object earlySingletonReference = getSingleton(beanName, false);
  59. if (earlySingletonReference != null) {
  60. if (exposedObject == bean) {
  61. exposedObject = earlySingletonReference;
  62. }
  63. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  64. String[] dependentBeans = getDependentBeans(beanName);
  65. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  66. for (String dependentBean : dependentBeans) {
  67. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  68. actualDependentBeans.add(dependentBean);
  69. }
  70. }
  71. if (!actualDependentBeans.isEmpty()) {
  72. throw new BeanCurrentlyInCreationException(beanName,
  73. "Bean with name '" + beanName + "' has been injected into other beans [" +
  74. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  75. "] in its raw version as part of a circular reference, but has eventually been " +
  76. "wrapped. This means that said other beans do not use the final version of the " +
  77. "bean. This is often the result of over-eager type matching - consider using " +
  78. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  79. }
  80. }
  81. }
  82. }
  83. // Register bean as disposable.
  84. try {
  85. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  86. }
  87. catch (BeanDefinitionValidationException ex) {
  88. throw new BeanCreationException(
  89. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  90. }
  91. return exposedObject;
  92. }
  1. 尝试从FactoryBean的缓存中获取
  2. 获取不到,则实例化bean
  3. MergedBeanDefinitionPostProcessor的应用,Autowired注解正是通过此方法实现诸如类型的预解析
  4. 依赖处理:若允许循环依赖,需要将bean提前放入三级缓存中
  5. 属性填充
  6. 初始化bean
  7. 循环依赖检查
  8. 注册DisposableBean
  9. 完成创建并返回

    从FactoryBean获取

    FactoryBeanMap中存放的是 factoryBeanName —> FactoryBean#getObject()的对象;

    创建实例bean

    1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    2. // Make sure bean class is actually resolved at this point.
    3. Class<?> beanClass = resolveBeanClass(mbd, beanName);
    4. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
    5. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    6. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    7. }
    8. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    9. if (instanceSupplier != null) {
    10. return obtainFromSupplier(instanceSupplier, beanName);
    11. }
    12. if (mbd.getFactoryMethodName() != null) {
    13. return instantiateUsingFactoryMethod(beanName, mbd, args);
    14. }
    15. // Shortcut when re-creating the same bean...
    16. boolean resolved = false;
    17. boolean autowireNecessary = false;
    18. if (args == null) {
    19. synchronized (mbd.constructorArgumentLock) {
    20. if (mbd.resolvedConstructorOrFactoryMethod != null) {
    21. resolved = true;
    22. autowireNecessary = mbd.constructorArgumentsResolved;
    23. }
    24. }
    25. }
    26. if (resolved) {
    27. if (autowireNecessary) {
    28. return autowireConstructor(beanName, mbd, null, null);
    29. }
    30. else {
    31. return instantiateBean(beanName, mbd);
    32. }
    33. }
    34. // Candidate constructors for autowiring?
    35. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    36. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
    37. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
    38. return autowireConstructor(beanName, mbd, ctors, args);
    39. }
    40. // Preferred constructors for default construction?
    41. ctors = mbd.getPreferredConstructors();
    42. if (ctors != null) {
    43. return autowireConstructor(beanName, mbd, ctors, null);
    44. }
    45. // No special handling: simply use no-arg constructor.
    46. return instantiateBean(beanName, mbd);
    47. }
  10. 若RootBeanDefinition中存在factoryMethodName则使用instantiateUsingFactoryMethod

  11. 解析使用哪个构造函数,并用它进行实例化

    autowireConstructor(beanName, mbd, null, null)

    1. public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
    2. @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
    3. BeanWrapperImpl bw = new BeanWrapperImpl();
    4. this.beanFactory.initBeanWrapper(bw);
    5. Constructor<?> constructorToUse = null;
    6. ArgumentsHolder argsHolderToUse = null;
    7. Object[] argsToUse = null;
    8. if (explicitArgs != null) {
    9. argsToUse = explicitArgs;
    10. }
    11. else {
    12. Object[] argsToResolve = null;
    13. synchronized (mbd.constructorArgumentLock) {
    14. constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
    15. if (constructorToUse != null && mbd.constructorArgumentsResolved) {
    16. // Found a cached constructor...
    17. argsToUse = mbd.resolvedConstructorArguments;
    18. if (argsToUse == null) {
    19. argsToResolve = mbd.preparedConstructorArguments;
    20. }
    21. }
    22. }
    23. if (argsToResolve != null) {
    24. argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
    25. }
    26. }
    27. if (constructorToUse == null || argsToUse == null) {
    28. // Take specified constructors, if any.
    29. Constructor<?>[] candidates = chosenCtors;
    30. if (candidates == null) {
    31. Class<?> beanClass = mbd.getBeanClass();
    32. try {
    33. candidates = (mbd.isNonPublicAccessAllowed() ?
    34. beanClass.getDeclaredConstructors() : beanClass.getConstructors());
    35. }
    36. catch (Throwable ex) {
    37. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    38. "Resolution of declared constructors on bean Class [" + beanClass.getName() +
    39. "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
    40. }
    41. }
    42. if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
    43. Constructor<?> uniqueCandidate = candidates[0];
    44. if (uniqueCandidate.getParameterCount() == 0) {
    45. synchronized (mbd.constructorArgumentLock) {
    46. mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
    47. mbd.constructorArgumentsResolved = true;
    48. mbd.resolvedConstructorArguments = EMPTY_ARGS;
    49. }
    50. bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
    51. return bw;
    52. }
    53. }
    54. // Need to resolve the constructor.
    55. boolean autowiring = (chosenCtors != null ||
    56. mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
    57. ConstructorArgumentValues resolvedValues = null;
    58. int minNrOfArgs;
    59. if (explicitArgs != null) {
    60. minNrOfArgs = explicitArgs.length;
    61. }
    62. else {
    63. ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
    64. resolvedValues = new ConstructorArgumentValues();
    65. minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
    66. }
    67. AutowireUtils.sortConstructors(candidates);
    68. int minTypeDiffWeight = Integer.MAX_VALUE;
    69. Set<Constructor<?>> ambiguousConstructors = null;
    70. Deque<UnsatisfiedDependencyException> causes = null;
    71. for (Constructor<?> candidate : candidates) {
    72. int parameterCount = candidate.getParameterCount();
    73. if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
    74. // Already found greedy constructor that can be satisfied ->
    75. // do not look any further, there are only less greedy constructors left.
    76. break;
    77. }
    78. if (parameterCount < minNrOfArgs) {
    79. continue;
    80. }
    81. ArgumentsHolder argsHolder;
    82. Class<?>[] paramTypes = candidate.getParameterTypes();
    83. if (resolvedValues != null) {
    84. try {
    85. String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
    86. if (paramNames == null) {
    87. ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
    88. if (pnd != null) {
    89. paramNames = pnd.getParameterNames(candidate);
    90. }
    91. }
    92. argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
    93. getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
    94. }
    95. catch (UnsatisfiedDependencyException ex) {
    96. if (logger.isTraceEnabled()) {
    97. logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
    98. }
    99. // Swallow and try next constructor.
    100. if (causes == null) {
    101. causes = new ArrayDeque<>(1);
    102. }
    103. causes.add(ex);
    104. continue;
    105. }
    106. }
    107. else {
    108. // Explicit arguments given -> arguments length must match exactly.
    109. if (parameterCount != explicitArgs.length) {
    110. continue;
    111. }
    112. argsHolder = new ArgumentsHolder(explicitArgs);
    113. }
    114. int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
    115. argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
    116. // Choose this constructor if it represents the closest match.
    117. if (typeDiffWeight < minTypeDiffWeight) {
    118. constructorToUse = candidate;
    119. argsHolderToUse = argsHolder;
    120. argsToUse = argsHolder.arguments;
    121. minTypeDiffWeight = typeDiffWeight;
    122. ambiguousConstructors = null;
    123. }
    124. else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
    125. if (ambiguousConstructors == null) {
    126. ambiguousConstructors = new LinkedHashSet<>();
    127. ambiguousConstructors.add(constructorToUse);
    128. }
    129. ambiguousConstructors.add(candidate);
    130. }
    131. }
    132. if (constructorToUse == null) {
    133. if (causes != null) {
    134. UnsatisfiedDependencyException ex = causes.removeLast();
    135. for (Exception cause : causes) {
    136. this.beanFactory.onSuppressedException(cause);
    137. }
    138. throw ex;
    139. }
    140. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    141. "Could not resolve matching constructor " +
    142. "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
    143. }
    144. else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
    145. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    146. "Ambiguous constructor matches found in bean '" + beanName + "' " +
    147. "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
    148. ambiguousConstructors);
    149. }
    150. if (explicitArgs == null && argsHolderToUse != null) {
    151. argsHolderToUse.storeCache(mbd, constructorToUse);
    152. }
    153. }
    154. Assert.state(argsToUse != null, "Unresolved constructor arguments");
    155. bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
    156. return bw;
    157. }
  12. 构造函数参数的确定

  • 若入参中传入了explicitArgs,则直接确定参数,进而确定使用哪个构造函数。
  • 从缓存中获取
  • 分析xml配置文件中的信息
  1. 构造函数确定
  • 根据参数的个数进行匹配
  • 若指定参数名,可以通过ParameterNameDiscoverer工具类获取
  1. 转换对应的参数类型
  2. 构造函数不确定性验证
  3. 根据实例化策略实例化bean

    instantiateBean(beanName, mbd);

    无参的,也就是没有必要注入其他依赖的情况

    1. protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
    2. try {
    3. Object beanInstance;
    4. if (System.getSecurityManager() != null) {
    5. beanInstance = AccessController.doPrivileged(
    6. (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
    7. getAccessControlContext());
    8. }
    9. else {
    10. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
    11. }
    12. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
    13. initBeanWrapper(bw);
    14. return bw;
    15. }
    16. catch (Throwable ex) {
    17. throw new BeanCreationException(
    18. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    19. }
    20. }

    根据实例化策略进行实例化

    实例化策略

    上面实例化bean都涉及了一个实例化策略的问题
    image.png

  4. 若没有look-up或者replace-method方法,则直接反射

  5. 否则,通过Cblib创建

    记录创建bean的ObjectFactory

    1. // Eagerly cache singletons to be able to resolve circular references
    2. // even when triggered by lifecycle interfaces like BeanFactoryAware.
    3. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
    4. isSingletonCurrentlyInCreation(beanName));
    5. if (earlySingletonExposure) {
    6. if (logger.isTraceEnabled()) {
    7. logger.trace("Eagerly caching bean '" + beanName +
    8. "' to allow for resolving potential circular references");
    9. }
    10. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    11. }

    image.png

    getEarlyBeanReference

    1. protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    2. Object exposedObject = bean;
    3. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    4. for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
    5. exposedObject = bp.getEarlyBeanReference(exposedObject, beanName);
    6. }
    7. }
    8. return exposedObject;
    9. }
  6. 调用了SmartInstantiationAwareBeanPostProcessor的处理器方法

    属性注入

    1. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    2. if (bw == null) {
    3. if (mbd.hasPropertyValues()) {
    4. throw new BeanCreationException(
    5. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
    6. }
    7. else {
    8. // Skip property population phase for null instance.
    9. return;
    10. }
    11. }
    12. // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    13. // state of the bean before properties are set. This can be used, for example,
    14. // to support styles of field injection.
    15. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    16. for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
    17. if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
    18. return;
    19. }
    20. }
    21. }
    22. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    23. int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    24. if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
    25. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
    26. // Add property values based on autowire by name if applicable.
    27. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
    28. autowireByName(beanName, mbd, bw, newPvs);
    29. }
    30. // Add property values based on autowire by type if applicable.
    31. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
    32. autowireByType(beanName, mbd, bw, newPvs);
    33. }
    34. pvs = newPvs;
    35. }
    36. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    37. boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
    38. PropertyDescriptor[] filteredPds = null;
    39. if (hasInstAwareBpps) {
    40. if (pvs == null) {
    41. pvs = mbd.getPropertyValues();
    42. }
    43. for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
    44. PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
    45. if (pvsToUse == null) {
    46. if (filteredPds == null) {
    47. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
    48. }
    49. pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
    50. if (pvsToUse == null) {
    51. return;
    52. }
    53. }
    54. pvs = pvsToUse;
    55. }
    56. }
    57. if (needsDepCheck) {
    58. if (filteredPds == null) {
    59. filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
    60. }
    61. checkDependencies(beanName, mbd, filteredPds, pvs);
    62. }
    63. if (pvs != null) {
    64. applyPropertyValues(beanName, mbd, bw, pvs);
    65. }
    66. }
  7. 执行InstantiationAwareBeanPostProcessor,此函数可以控制是否继续进行属性填充

  8. 获取propertyValues,并根据装配类型,补充PropertyValues
  9. 应用InstantiationAwareBeanPostProcessor处理器的postProcessPropertyValues方法,对属性获取完毕填充前对属性的再次处理,典型应用是RequiredAnnotationBeanPostProcessor类中对属性的验证
  10. 将所有PropertyValues中的属性填充至BeanWrapper中

    autowireByName

autowireByType

初始化bean

  1. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. invokeAwareMethods(beanName, bean);
  5. return null;
  6. }, getAccessControlContext());
  7. }
  8. else {
  9. invokeAwareMethods(beanName, bean);
  10. }
  11. Object wrappedBean = bean;
  12. if (mbd == null || !mbd.isSynthetic()) {
  13. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  14. }
  15. try {
  16. invokeInitMethods(beanName, wrappedBean, mbd);
  17. }
  18. catch (Throwable ex) {
  19. throw new BeanCreationException(
  20. (mbd != null ? mbd.getResourceDescription() : null),
  21. beanName, "Invocation of init method failed", ex);
  22. }
  23. if (mbd == null || !mbd.isSynthetic()) {
  24. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  25. }
  26. return wrappedBean;
  27. }

调用Aware方法

Aware方法只对以下方法进行注入

  1. private void invokeAwareMethods(String beanName, Object bean) {
  2. if (bean instanceof Aware) {
  3. if (bean instanceof BeanNameAware) {
  4. ((BeanNameAware) bean).setBeanName(beanName);
  5. }
  6. if (bean instanceof BeanClassLoaderAware) {
  7. ClassLoader bcl = getBeanClassLoader();
  8. if (bcl != null) {
  9. ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
  10. }
  11. }
  12. if (bean instanceof BeanFactoryAware) {
  13. ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
  14. }
  15. }
  16. }
  1. BeanNameAware
  2. BeanClassLoaderAware
  3. BeanFactoryAware

    处理器的应用

    1. Object wrappedBean = bean;
    2. if (mbd == null || !mbd.isSynthetic()) {
    3. //before
    4. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    5. }
    6. try {
    7. //。。。。。
    8. invokeInitMethods(beanName, wrappedBean, mbd);
    9. }
    10. catch (Throwable ex) {
    11. throw new BeanCreationException(
    12. (mbd != null ? mbd.getResourceDescription() : null),
    13. beanName, "Invocation of init method failed", ex);
    14. }
    15. if (mbd == null || !mbd.isSynthetic()) {
    16. //after
    17. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    18. }

    调用初始化方法前后分别使用BeanPostProcessorpostProcessBeforeInitializationpostProcessAfterInitialization

    自定义init方法

    1. protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
    2. throws Throwable {
    3. boolean isInitializingBean = (bean instanceof InitializingBean);
    4. if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
    5. if (logger.isTraceEnabled()) {
    6. logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
    7. }
    8. if (System.getSecurityManager() != null) {
    9. try {
    10. AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
    11. ((InitializingBean) bean).afterPropertiesSet();
    12. return null;
    13. }, getAccessControlContext());
    14. }
    15. catch (PrivilegedActionException pae) {
    16. throw pae.getException();
    17. }
    18. }
    19. else {
    20. ((InitializingBean) bean).afterPropertiesSet();
    21. }
    22. }
    23. if (mbd != null && bean.getClass() != NullBean.class) {
    24. String initMethodName = mbd.getInitMethodName();
    25. if (StringUtils.hasLength(initMethodName) &&
    26. !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
    27. !mbd.isExternallyManagedInitMethod(initMethodName)) {
    28. invokeCustomInitMethod(beanName, bean, mbd);
    29. }
    30. }
    31. }
  4. InitializingBeanafterPropertiesSet()

  5. invokeCustomInitMethod调用自定义初始化方法

注册DisposableBean

  1. protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
  2. AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
  3. if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
  4. if (mbd.isSingleton()) {
  5. // Register a DisposableBean implementation that performs all destruction
  6. // work for the given bean: DestructionAwareBeanPostProcessors,
  7. // DisposableBean interface, custom destroy method.
  8. registerDisposableBean(beanName, new DisposableBeanAdapter(
  9. bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
  10. }
  11. else {
  12. // A bean with a custom scope...
  13. Scope scope = this.scopes.get(mbd.getScope());
  14. if (scope == null) {
  15. throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
  16. }
  17. scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(
  18. bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
  19. }
  20. }
  21. }
  1. public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
  2. List<DestructionAwareBeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) {
  3. Assert.notNull(bean, "Disposable bean must not be null");
  4. this.bean = bean;
  5. this.beanName = beanName;
  6. this.invokeDisposableBean =
  7. (this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
  8. this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
  9. this.acc = acc;
  10. String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
  11. if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
  12. !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
  13. this.destroyMethodName = destroyMethodName;
  14. Method destroyMethod = determineDestroyMethod(destroyMethodName);
  15. if (destroyMethod == null) {
  16. if (beanDefinition.isEnforceDestroyMethod()) {
  17. throw new BeanDefinitionValidationException("Could not find a destroy method named '" +
  18. destroyMethodName + "' on bean with name '" + beanName + "'");
  19. }
  20. }
  21. else {
  22. if (destroyMethod.getParameterCount() > 0) {
  23. Class<?>[] paramTypes = destroyMethod.getParameterTypes();
  24. if (paramTypes.length > 1) {
  25. throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
  26. beanName + "' has more than one parameter - not supported as destroy method");
  27. }
  28. else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) {
  29. throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
  30. beanName + "' has a non-boolean parameter - not supported as destroy method");
  31. }
  32. }
  33. destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod);
  34. }
  35. this.destroyMethod = destroyMethod;
  36. }
  37. this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
  38. }
  1. DestructionAwareBeanPostProcessor
  2. DisposableBean/destroy-method

如上的两个内容都会被注册