show: stepversion: 1.0
enable_checker: true

浅谈SpringFramework Bean创建过程

文章前言

提示:在前面的学习中,我们对BeanFactory的创建过程有了一个熟悉,其实实际的操作不止创建BeanFactory,调用的过程也实现了将xml解析为Document对象,再转换成BeanDefinition(很重要,Spring的Bean),并注册到BeanFactory,接着本文带着疑问学习一下Spring中的Bean(BeanDefinition)是怎么创建实例出来的?
提示:以下是本篇文章正文内容,下面案例可供参考

BeanDefinition实例过程简介

上一章学习了obtainFreshBeanFactory这个方法,经过这个方法,xml配置信息已经转换成一个BeanDefinition,但是BeanDefinition还没实例,属性也没配置,只是配置信息被提取出来,而且注册到BeanFactory
在这里插入图片描述
在之前文章学习,我们知道了,Bean的实例完成是在finishBeanFactoryInitialization这一步,当然是针对非懒加载的单例bean,多例的情况,后面有时间再来学习
在这里插入图片描述

finishBeanFactoryInitialization实现

ok,有了前面的简单了解,可以开始学习finishBeanFactoryInitialization的创建过程:通过代码,一步步跟,看看BeanDefinition是怎么初始化的?bean属性是怎么填充的?

  1. /**
  2. * Finish the initialization of this context's bean factory,
  3. * initializing all remaining singleton beans.
  4. */
  5. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  6. // Initialize conversion service for this context.
  7. // 初始化ConversionService,这个bean用于将前端传过来的参数和后端的 controller 方法上的参数进行绑定
  8. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  9. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  10. beanFactory.setConversionService(
  11. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  12. }
  13. // Register a default embedded value resolver if no bean post-processor
  14. // (such as a PropertyPlaceholderConfigurer bean) registered any before:
  15. // at this point, primarily for resolution in annotation attribute values.
  16. if (!beanFactory.hasEmbeddedValueResolver()) {
  17. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  18. }
  19. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  20. // 先初始化LoadTimeWeaverAware 类型的Bean
  21. // AspectJ 的内容,IoC的源码学习,先跳过
  22. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  23. for (String weaverAwareName : weaverAwareNames) {
  24. getBean(weaverAwareName);
  25. }
  26. // Stop using the temporary ClassLoader for type matching.
  27. beanFactory.setTempClassLoader(null);
  28. // Allow for caching all bean definition metadata, not expecting further changes.
  29. // 冻结配置,不让bean 定义解析、加载、注册
  30. beanFactory.freezeConfiguration();
  31. // Instantiate all remaining (non-lazy-init) singletons.
  32. // 实例所有非懒加载的单例Bean
  33. beanFactory.preInstantiateSingletons();
  34. }

{@link org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons}

  1. @Override
  2. public void preInstantiateSingletons() throws BeansException {
  3. if (logger.isDebugEnabled()) {
  4. logger.debug("Pre-instantiating singletons in " + this);
  5. }
  6. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  7. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  8. // 获取beanName列表,this.beanDefinitionNames 保存了所有的 beanNames
  9. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  10. // Trigger initialization of all non-lazy singleton beans...
  11. // 触发所有非懒加载的单例bean初始化操作(lazy-init=false)
  12. for (String beanName : beanNames) {
  13. // 合并rootBean中的配置, <bean id="a" class="a" parent="p" />
  14. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  15. // 非抽象(abstract = false)、非懒加载(lazy-init=false)的单例Bean(scope=singleton)
  16. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  17. // 处理FactoryBean,注意对比BeanFactory和FactoryBean
  18. if (isFactoryBean(beanName)) {
  19. // factoryBean调用在beanName加载前缀符号‘&’
  20. // 为什么要加‘&’,应该是做下标记,不过在bean创建过程要进行转换,详情请看下文
  21. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  22. if (bean instanceof FactoryBean) {
  23. FactoryBean<?> factory = (FactoryBean<?>) bean;
  24. boolean isEagerInit;
  25. // FactoryBean是SmartFactoryBean 的基类
  26. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  27. isEagerInit = AccessController.doPrivileged(
  28. (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
  29. getAccessControlContext());
  30. }
  31. else {
  32. isEagerInit = (factory instanceof SmartFactoryBean &&
  33. ((SmartFactoryBean<?>) factory).isEagerInit());
  34. }
  35. if (isEagerInit) {
  36. getBean(beanName);
  37. }
  38. }
  39. }
  40. else {
  41. // 普通的Bean,调这个方法进行实例,往下跟
  42. getBean(beanName);
  43. }
  44. }
  45. }
  46. // Trigger post-initialization callback for all applicable beans...
  47. // SmartInitializingSingleton 的基类在这里回调
  48. for (String beanName : beanNames) {
  49. Object singletonInstance = getSingleton(beanName);
  50. if (singletonInstance instanceof SmartInitializingSingleton) {
  51. SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  52. if (System.getSecurityManager() != null) {
  53. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  54. smartSingleton.afterSingletonsInstantiated();
  55. return null;
  56. }, getAccessControlContext());
  57. }
  58. else {
  59. smartSingleton.afterSingletonsInstantiated();
  60. }
  61. }
  62. }
  63. }

AbstractBeanFactory.java
{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}

  1. @Override
  2. public Object getBean(String name) throws BeansException {
  3. // 往下跟
  4. return doGetBean(name, null, null, false);
  5. }

{@link org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean}

  1. /**
  2. * Return an instance, which may be shared or independent, of the specified bean.
  3. * @param name the name of the bean to retrieve
  4. * @param requiredType the required type of the bean to retrieve
  5. * @param args arguments to use when creating a bean instance using explicit arguments
  6. * (only applied when creating a new instance as opposed to retrieving an existing one)
  7. * @param typeCheckOnly whether the instance is obtained for a type check,
  8. * not for actual use
  9. * @return an instance of the bean
  10. * @throws BeansException if the bean could not be created
  11. */
  12. @SuppressWarnings("unchecked")
  13. protected <T> T doGetBean(
  14. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  15. throws BeansException {
  16. // 处理BeanName,前面说的FactoryBean带‘&’符号,要在这里进行转换
  17. String beanName = transformedBeanName(name);
  18. Object bean;
  19. // Eagerly check singleton cache for manually registered singletons.
  20. // 从map(singletonObjects)里获取单例bean,确定是否已经存在对应实例
  21. Object sharedInstance = getSingleton(beanName);
  22. if (sharedInstance != null && args == null) {
  23. if (logger.isDebugEnabled()) {
  24. if (isSingletonCurrentlyInCreation(beanName)) {
  25. logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
  26. "' that is not fully initialized yet - a consequence of a circular reference");
  27. }
  28. else {
  29. logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
  30. }
  31. }
  32. // 两种情况:普通的bean,直接从singletonObjects返回sharedInstance
  33. //如果是FactoryBean,返回其创建的对象实例
  34. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  35. }
  36. else {
  37. // Fail if we're already creating this bean instance:
  38. // We're assumably within a circular reference.
  39. // 为了避免循环引用,遇到这种情况,直接抛出异常
  40. if (isPrototypeCurrentlyInCreation(beanName)) {
  41. throw new BeanCurrentlyInCreationException(beanName);
  42. }
  43. // Check if bean definition exists in this factory.
  44. // 检查BeanFactory是否存在这个BeanDefinition
  45. BeanFactory parentBeanFactory = getParentBeanFactory();
  46. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  47. // Not found -> check parent.
  48. // 当前容器找不到BeanDefinition,去parent容器查询
  49. String nameToLookup = originalBeanName(name);
  50. if (parentBeanFactory instanceof AbstractBeanFactory) {
  51. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  52. nameToLookup, requiredType, args, typeCheckOnly);
  53. }
  54. else if (args != null) {
  55. // Delegation to parent with explicit args.
  56. // 返回parent容器的查询结果
  57. return (T) parentBeanFactory.getBean(nameToLookup, args);
  58. }
  59. else {
  60. // No args -> delegate to standard getBean method.
  61. return parentBeanFactory.getBean(nameToLookup, requiredType);
  62. }
  63. }
  64. if (!typeCheckOnly) {
  65. //typeCheckOnly为false的情况,将beanName放在一个alreadyCreated的集合
  66. markBeanAsCreated(beanName);
  67. }
  68. try {
  69. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  70. checkMergedBeanDefinition(mbd, beanName, args);
  71. // Guarantee initialization of beans that the current bean depends on.
  72. // 校验是否配置了 depends-on
  73. String[] dependsOn = mbd.getDependsOn();
  74. if (dependsOn != null) {
  75. for (String dep : dependsOn) {
  76. // 存在循环引用的情况,要抛出异常
  77. if (isDependent(beanName, dep)) {
  78. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  79. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  80. }
  81. // 正常情况,注册依赖关系
  82. registerDependentBean(dep, beanName);
  83. try {
  84. // 初始化被依赖项
  85. getBean(dep);
  86. }
  87. catch (NoSuchBeanDefinitionException ex) {
  88. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  89. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  90. }
  91. }
  92. }
  93. // Create bean instance.
  94. // 单例的Bean
  95. if (mbd.isSingleton()) {
  96. sharedInstance = getSingleton(beanName, () -> {
  97. try {
  98. // 创建单例bean
  99. return createBean(beanName, mbd, args);
  100. }
  101. catch (BeansException ex) {
  102. // Explicitly remove instance from singleton cache: It might have been put there
  103. // eagerly by the creation process, to allow for circular reference resolution.
  104. // Also remove any beans that received a temporary reference to the bean.
  105. destroySingleton(beanName);
  106. throw ex;
  107. }
  108. });
  109. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  110. }
  111. // 多例的Bean,scope = protoType
  112. else if (mbd.isPrototype()) {
  113. // It's a prototype -> create a new instance.
  114. Object prototypeInstance = null;
  115. try {
  116. beforePrototypeCreation(beanName);
  117. // 执行多例Bean创建
  118. prototypeInstance = createBean(beanName, mbd, args);
  119. }
  120. finally {
  121. afterPrototypeCreation(beanName);
  122. }
  123. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  124. }
  125. // 如果不是单例bean也不是多例的bean,委托给对应的实现类
  126. else {
  127. String scopeName = mbd.getScope();
  128. if (!StringUtils.hasLength(scopeName)) {
  129. throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
  130. }
  131. Scope scope = this.scopes.get(scopeName);
  132. if (scope == null) {
  133. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  134. }
  135. try {
  136. Object scopedInstance = scope.get(beanName, () -> {
  137. beforePrototypeCreation(beanName);
  138. try {
  139. // 执行bean创建
  140. return createBean(beanName, mbd, args);
  141. }
  142. finally {
  143. afterPrototypeCreation(beanName);
  144. }
  145. });
  146. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  147. }
  148. catch (IllegalStateException ex) {
  149. throw new BeanCreationException(beanName,
  150. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  151. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  152. ex);
  153. }
  154. }
  155. }
  156. catch (BeansException ex) {
  157. cleanupAfterBeanCreationFailure(beanName);
  158. throw ex;
  159. }
  160. }
  161. // Check if required type matches the type of the actual bean instance.
  162. // 检查一下类型是否正确,不正确抛出异常,正确返回实例
  163. if (requiredType != null && !requiredType.isInstance(bean)) {
  164. try {
  165. T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
  166. if (convertedBean == null) {
  167. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  168. }
  169. return convertedBean;
  170. }
  171. catch (TypeMismatchException ex) {
  172. if (logger.isDebugEnabled()) {
  173. logger.debug("Failed to convert bean '" + name + "' to required type '" +
  174. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  175. }
  176. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  177. }
  178. }
  179. return (T) bean;
  180. }

补充前面说的FactoryBean带‘&’符号问题可以在transformedBeanName看到原因
{@link org.springframework.beans.factory.support.AbstractBeanFactory#transformedBeanName}

  1. /**
  2. * Return the bean name, stripping out the factory dereference prefix if necessary,
  3. * and resolving aliases to canonical names.
  4. * @param name the user-specified name
  5. * @return the transformed bean name
  6. */
  7. protected String transformedBeanName(String name) {
  8. // 往下跟
  9. return canonicalName(BeanFactoryUtils.transformedBeanName(name));
  10. }
  1. /**
  2. * Return the actual bean name, stripping out the factory dereference
  3. * prefix (if any, also stripping repeated factory prefixes if found).
  4. * @param name the name of the bean
  5. * @return the transformed name
  6. * @see BeanFactory#FACTORY_BEAN_PREFIX
  7. */
  8. public static String transformedBeanName(String name) {
  9. Assert.notNull(name, "'name' must not be null");
  10. String beanName = name;
  11. // FactoryBean的beanName是带‘&’的
  12. while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
  13. beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
  14. }
  15. return beanName;
  16. }

{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean}

  1. /**
  2. * Central method of this class: creates a bean instance,
  3. * populates the bean instance, applies post-processors, etc.
  4. * @see #doCreateBean
  5. */
  6. @Override
  7. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  8. throws BeanCreationException {
  9. if (logger.isDebugEnabled()) {
  10. logger.debug("Creating instance of bean '" + beanName + "'");
  11. }
  12. RootBeanDefinition mbdToUse = mbd;
  13. // Make sure bean class is actually resolved at this point, and
  14. // clone the bean definition in case of a dynamically resolved Class
  15. // which cannot be stored in the shared merged bean definition.
  16. // ClassLoader加载BeanDefinition
  17. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  18. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  19. mbdToUse = new RootBeanDefinition(mbd);
  20. mbdToUse.setBeanClass(resolvedClass);
  21. }
  22. // Prepare method overrides.
  23. // 处理方法覆盖
  24. // todo 涉及bean 定义中的 <lookup-method /> 和 <replaced-method />,先放过
  25. try {
  26. mbdToUse.prepareMethodOverrides();
  27. }
  28. catch (BeanDefinitionValidationException ex) {
  29. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  30. beanName, "Validation of method overrides failed", ex);
  31. }
  32. try {
  33. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  34. // todo 让InstantiationAwareBeanPostProcessor这个后置处理器有机会返回一个代理的实例,这个ioc源码学习先放过
  35. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  36. if (bean != null) {
  37. return bean;
  38. }
  39. }
  40. catch (Throwable ex) {
  41. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  42. "BeanPostProcessor before instantiation of bean failed", ex);
  43. }
  44. try {
  45. // 重头戏,doCreateBean是实践执行bean创建的
  46. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  47. if (logger.isDebugEnabled()) {
  48. logger.debug("Finished creating instance of bean '" + beanName + "'");
  49. }
  50. return beanInstance;
  51. }
  52. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  53. // A previously detected exception with proper bean creation context already,
  54. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  55. throw ex;
  56. }
  57. catch (Throwable ex) {
  58. throw new BeanCreationException(
  59. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  60. }
  61. }

继续跟doCreateBean

  1. /**
  2. * Actually create the specified bean. Pre-creation processing has already happened
  3. * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
  4. * <p>Differentiates between default bean instantiation, use of a
  5. * factory method, and autowiring a constructor.
  6. * @param beanName the name of the bean
  7. * @param mbd the merged bean definition for the bean
  8. * @param args explicit arguments to use for constructor or factory method invocation
  9. * @return a new instance of the bean
  10. * @throws BeanCreationException if the bean could not be created
  11. * @see #instantiateBean
  12. * @see #instantiateUsingFactoryMethod
  13. * @see #autowireConstructor
  14. */
  15. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  16. throws BeanCreationException {
  17. // Instantiate the bean.
  18. BeanWrapper instanceWrapper = null;
  19. if (mbd.isSingleton()) {
  20. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  21. }
  22. // 不是FactoryBean的情况
  23. if (instanceWrapper == null) {
  24. // 创建Bean实例,但是还没设置属性
  25. instanceWrapper = createBeanInstance(beanName, mbd, args);
  26. }
  27. Object bean = instanceWrapper.getWrappedInstance();
  28. Class<?> beanType = instanceWrapper.getWrappedClass();
  29. if (beanType != NullBean.class) {
  30. mbd.resolvedTargetType = beanType;
  31. }
  32. // Allow post-processors to modify the merged bean definition.
  33. // 涉及到MergedBeanDefinitionPostProcessor,先跳过 todo
  34. synchronized (mbd.postProcessingLock) {
  35. if (!mbd.postProcessed) {
  36. try {
  37. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  38. }
  39. catch (Throwable ex) {
  40. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  41. "Post-processing of merged bean definition failed", ex);
  42. }
  43. mbd.postProcessed = true;
  44. }
  45. }
  46. // Eagerly cache singletons to be able to resolve circular references
  47. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  48. // 循环依赖的问题,先跳过 todo
  49. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  50. isSingletonCurrentlyInCreation(beanName));
  51. if (earlySingletonExposure) {
  52. if (logger.isDebugEnabled()) {
  53. logger.debug("Eagerly caching bean '" + beanName +
  54. "' to allow for resolving potential circular references");
  55. }
  56. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  57. }
  58. // Initialize the bean instance.
  59. Object exposedObject = bean;
  60. try {
  61. // 关键一步,Bean属性填充
  62. populateBean(beanName, mbd, instanceWrapper);
  63. // 调用初始化方法,应用BeanPostProcess后置处理器
  64. exposedObject = initializeBean(beanName, exposedObject, mbd);
  65. }
  66. catch (Throwable ex) {
  67. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  68. throw (BeanCreationException) ex;
  69. }
  70. else {
  71. throw new BeanCreationException(
  72. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  73. }
  74. }
  75. if (earlySingletonExposure) {
  76. Object earlySingletonReference = getSingleton(beanName, false);
  77. if (earlySingletonReference != null) {
  78. if (exposedObject == bean) {
  79. exposedObject = earlySingletonReference;
  80. }
  81. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  82. String[] dependentBeans = getDependentBeans(beanName);
  83. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  84. for (String dependentBean : dependentBeans) {
  85. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  86. actualDependentBeans.add(dependentBean);
  87. }
  88. }
  89. if (!actualDependentBeans.isEmpty()) {
  90. throw new BeanCurrentlyInCreationException(beanName,
  91. "Bean with name '" + beanName + "' has been injected into other beans [" +
  92. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  93. "] in its raw version as part of a circular reference, but has eventually been " +
  94. "wrapped. This means that said other beans do not use the final version of the " +
  95. "bean. This is often the result of over-eager type matching - consider using " +
  96. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  97. }
  98. }
  99. }
  100. }
  101. // Register bean as disposable.
  102. try {
  103. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  104. }
  105. catch (BeanDefinitionValidationException ex) {
  106. throw new BeanCreationException(
  107. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  108. }
  109. return exposedObject;
  110. }

看一下关键的createBeanInstance方法,这是创建bean实例的方法:

  1. /**
  2. * Create a new instance for the specified bean, using an appropriate instantiation strategy:
  3. * factory method, constructor autowiring, or simple instantiation.
  4. * @param beanName the name of the bean
  5. * @param mbd the bean definition for the bean
  6. * @param args explicit arguments to use for constructor or factory method invocation
  7. * @return a BeanWrapper for the new instance
  8. * @see #obtainFromSupplier
  9. * @see #instantiateUsingFactoryMethod
  10. * @see #autowireConstructor
  11. * @see #instantiateBean
  12. */
  13. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  14. // Make sure bean class is actually resolved at this point.
  15. // 确保classloader加载了此bean class
  16. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  17. // 校验这个bean权限是否是public的
  18. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  19. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  20. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  21. }
  22. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  23. if (instanceSupplier != null) {
  24. return obtainFromSupplier(instanceSupplier, beanName);
  25. }
  26. if (mbd.getFactoryMethodName() != null) {
  27. // 采用工厂方法实例化
  28. return instantiateUsingFactoryMethod(beanName, mbd, args);
  29. }
  30. // Shortcut when re-creating the same bean...
  31. // 判断是否第一次构建,第一次构建采用无参构造函数,还是构造函数依赖注入
  32. boolean resolved = false;
  33. boolean autowireNecessary = false;
  34. if (args == null) {
  35. synchronized (mbd.constructorArgumentLock) {
  36. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  37. resolved = true;
  38. autowireNecessary = mbd.constructorArgumentsResolved;
  39. }
  40. }
  41. }
  42. if (resolved) {
  43. if (autowireNecessary) {
  44. // 构造函数注入
  45. return autowireConstructor(beanName, mbd, null, null);
  46. }
  47. else {
  48. // 无参构造函数
  49. return instantiateBean(beanName, mbd);
  50. }
  51. }
  52. // Candidate constructors for autowiring?
  53. // 判断是否采用有参构造函数
  54. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  55. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
  56. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  57. // 有参构造函数依赖注入
  58. return autowireConstructor(beanName, mbd, ctors, args);
  59. }
  60. // No special handling: simply use no-arg constructor.
  61. // 调用无参构造函数
  62. return instantiateBean(beanName, mbd);
  63. }

跳最简单的无参构造函数注入方法instantiateBean

  1. /**
  2. * Instantiate the given bean using its default constructor.
  3. * @param beanName the name of the bean
  4. * @param mbd the bean definition for the bean
  5. * @return a BeanWrapper for the new instance
  6. */
  7. protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
  8. try {
  9. Object beanInstance;
  10. if (System.getSecurityManager() != null) {
  11. beanInstance = AccessController.doPrivileged(
  12. (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
  13. getAccessControlContext());
  14. }
  15. else {
  16. // 重点,实例过程
  17. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
  18. }
  19. // BeanWrapper封装一下,返回
  20. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  21. initBeanWrapper(bw);
  22. return bw;
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanCreationException(
  26. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  27. }
  28. }

{@link org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate}

  1. @Override
  2. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  3. // Don't override the class with CGLIB if no overrides.
  4. // 不存在方法覆写的情况,利用java的反射(JDK API)就能实现实例,方法覆写详情参考lookup-method 和 replaced-method
  5. if (!bd.hasMethodOverrides()) {
  6. Constructor<?> constructorToUse;
  7. synchronized (bd.constructorArgumentLock) {
  8. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  9. if (constructorToUse == null) {
  10. final Class<?> clazz = bd.getBeanClass();
  11. if (clazz.isInterface()) {
  12. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  13. }
  14. try {
  15. if (System.getSecurityManager() != null) {
  16. constructorToUse = AccessController.doPrivileged(
  17. (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
  18. }
  19. else {
  20. constructorToUse = clazz.getDeclaredConstructor();
  21. }
  22. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  26. }
  27. }
  28. }
  29. // 调用BeanUtils对构造方法进行实例
  30. return BeanUtils.instantiateClass(constructorToUse);
  31. }
  32. else {
  33. // Must generate CGLIB subclass.
  34. // 存在方法覆写的情况:SimpleInstantiationStrategy并没有提供实例化支持(JDK不支持),
  35. // 只能通过动态代理CGLIB实现,这是一个模板方法,给子类继承实现
  36. return instantiateWithMethodInjection(bd, beanName, owner);
  37. }
  38. }

ok,前面是对bean实例过程的描述,接着继续跟一个关键点,Bean属性的填充,代码往上翻,找到{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean}找到代码populateBean(beanName, mbd, instanceWrapper);

  1. /**
  2. * Populate the bean instance in the given BeanWrapper with the property values
  3. * from the bean definition.
  4. * @param beanName the name of the bean
  5. * @param mbd the bean definition for the bean
  6. * @param bw the BeanWrapper with bean instance
  7. */
  8. protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  9. if (bw == null) {
  10. // bean是否有属性
  11. if (mbd.hasPropertyValues()) {
  12. throw new BeanCreationException(
  13. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
  14. }
  15. else {
  16. // Skip property population phase for null instance.
  17. return;
  18. }
  19. }
  20. // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
  21. // state of the bean before properties are set. This can be used, for example,
  22. // to support styles of field injection.
  23. // 这个校验有点看不太懂 先跳过 todo
  24. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  25. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  26. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  27. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  28. // 返回false,代表不需要进行后续的属性设值,也不需要调用后置处理器
  29. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  30. return;
  31. }
  32. }
  33. }
  34. }
  35. PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
  36. int resolvedAutowireMode = mbd.getResolvedAutowireMode();
  37. if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  38. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  39. // Add property values based on autowire by name if applicable.
  40. // 通过beanname找到属性值
  41. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
  42. autowireByName(beanName, mbd, bw, newPvs);
  43. }
  44. // Add property values based on autowire by type if applicable.
  45. // 通用类型装配
  46. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
  47. autowireByType(beanName, mbd, bw, newPvs);
  48. }
  49. pvs = newPvs;
  50. }
  51. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  52. boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
  53. if (hasInstAwareBpps || needsDepCheck) {
  54. if (pvs == null) {
  55. pvs = mbd.getPropertyValues();
  56. }
  57. PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  58. if (hasInstAwareBpps) {
  59. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  60. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  61. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  62. // 后置处理器的内容,很重要的方面,不过内容比较多,先跳过
  63. pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  64. if (pvs == null) {
  65. return;
  66. }
  67. }
  68. }
  69. }
  70. if (needsDepCheck) {
  71. checkDependencies(beanName, mbd, filteredPds, pvs);
  72. }
  73. }
  74. if (pvs != null) {
  75. //设置 bean 实例的属性值
  76. applyPropertyValues(beanName, mbd, bw, pvs);
  77. }
  78. }

文章归纳

提示:这里对文章进行归纳:ok,本文对BeanDefinition的实例过程进行简单的学习,Spring源码比较复杂,需要慢慢积累,才能对整个框架有很好的理解,这款框架有一个很值得学习的地方是很好地做到的面向接口编程,很多地方也用到了模板方法设计模式,工厂模式,等等,很好地应用了设计模式,针对BeanDefinition创建的过程,都有提供一些接口给子类拓展,框架就显得灵活,可拓展