源码图

Spring源码 (2).png

生命周期流程图

Spring IOC-bean生命周期 - 图3

Spring IOC Bean生命周期源码

启动spring

  1. public static void main(String[] args) {
  2. ApplicationContext ac = new AnnotationConfigApplicationContext(AppConf.class);
  3. UserService userService = ac.getBean(UserService.class);
  4. userService.fun1();
  5. }

进入 ApplicationContext ac = new AnnotationConfigApplicationContext(AppConf.class); 方法

  1. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  2. this();
  3. register(componentClasses);
  4. refresh();
  5. }

执行过程
image.png

进入refresh方法

  1. public void refresh() throws BeansException, IllegalStateException {
  2. synchronized (this.startupShutdownMonitor) {
  3. // Prepare this context for refreshing.
  4. prepareRefresh();
  5. // Tell the subclass to refresh the internal bean factory.
  6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  7. // Prepare the bean factory for use in this context.
  8. prepareBeanFactory(beanFactory);
  9. try {
  10. // Allows post-processing of the bean factory in context subclasses.
  11. postProcessBeanFactory(beanFactory);
  12. // Invoke factory processors registered as beans in the context.
  13. invokeBeanFactoryPostProcessors(beanFactory);
  14. // Register bean processors that intercept bean creation.
  15. registerBeanPostProcessors(beanFactory);
  16. // Initialize message source for this context.
  17. initMessageSource();
  18. // Initialize event multicaster for this context.
  19. initApplicationEventMulticaster();
  20. // Initialize other special beans in specific context subclasses.
  21. onRefresh();
  22. // Check for listener beans and register them.
  23. registerListeners();
  24. // Instantiate all remaining (non-lazy-init) singletons.
  25. finishBeanFactoryInitialization(beanFactory);
  26. // Last step: publish corresponding event.
  27. finishRefresh();
  28. }
  29. catch (BeansException ex) {
  30. if (logger.isWarnEnabled()) {
  31. logger.warn("Exception encountered during context initialization - " +
  32. "cancelling refresh attempt: " + ex);
  33. }
  34. // Destroy already created singletons to avoid dangling resources.
  35. destroyBeans();
  36. // Reset 'active' flag.
  37. cancelRefresh(ex);
  38. // Propagate exception to caller.
  39. throw ex;
  40. }
  41. finally {
  42. // Reset common introspection caches in Spring's core, since we
  43. // might not ever need metadata for singleton beans anymore...
  44. resetCommonCaches();
  45. }
  46. }
  47. }

进入这个方法就是spring ioc 和 aop的 核心 后面有对这些方法的具体分析

进入finishBeanFactoryInitialization(beanFactory);

继续进入
// Instantiate all remaining (non-lazy-init)
singletons.beanFactory.preInstantiateSingletons();

继续进入 getBean(beanName); ——> doGetBean(name, null, null, false);

  1. protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
  2. @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
  3. final String beanName = transformedBeanName(name);
  4. Object bean;
  5. // Eagerly check singleton cache for manually registered singletons.
  6. //去缓存中获取bean 不管是getBean方法还是spring初始化的时候都是使用这个方法
  7. //就是都是先从缓存中获取bean
  8. Object sharedInstance = getSingleton(beanName);
  9. if (sharedInstance != null && args == null) {
  10. if (logger.isTraceEnabled()) {
  11. if (isSingletonCurrentlyInCreation(beanName)) {
  12. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  13. "' that is not fully initialized yet - a consequence of a circular reference");
  14. }
  15. else {
  16. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  17. }
  18. }
  19. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  20. }
  21. else {
  22. // Fail if we're already creating this bean instance:
  23. // We're assumably within a circular reference.
  24. if (isPrototypeCurrentlyInCreation(beanName)) {
  25. throw new BeanCurrentlyInCreationException(beanName);
  26. }
  27. // Check if bean definition exists in this factory.
  28. BeanFactory parentBeanFactory = getParentBeanFactory();
  29. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  30. // Not found -> check parent.
  31. String nameToLookup = originalBeanName(name);
  32. if (parentBeanFactory instanceof AbstractBeanFactory) {
  33. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  34. nameToLookup, requiredType, args, typeCheckOnly);
  35. }
  36. else if (args != null) {
  37. // Delegation to parent with explicit args.
  38. return (T) parentBeanFactory.getBean(nameToLookup, args);
  39. }
  40. else if (requiredType != null) {
  41. // No args -> delegate to standard getBean method.
  42. return parentBeanFactory.getBean(nameToLookup, requiredType);
  43. }
  44. else {
  45. return (T) parentBeanFactory.getBean(nameToLookup);
  46. }
  47. }
  48. if (!typeCheckOnly) {
  49. markBeanAsCreated(beanName);
  50. }
  51. try {
  52. final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  53. checkMergedBeanDefinition(mbd, beanName, args);
  54. // Guarantee initialization of beans that the current bean depends on.
  55. String[] dependsOn = mbd.getDependsOn();
  56. if (dependsOn != null) {
  57. for (String dep : dependsOn) {
  58. if (isDependent(beanName, dep)) {
  59. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  60. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  61. }
  62. registerDependentBean(dep, beanName);
  63. try {
  64. getBean(dep);
  65. }
  66. catch (NoSuchBeanDefinitionException ex) {
  67. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  68. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  69. }
  70. }
  71. }
  72. // Create bean instance.
  73. if (mbd.isSingleton()) {
  74. sharedInstance = getSingleton(beanName, () -> {
  75. try {
  76. return createBean(beanName, mbd, args);
  77. }
  78. catch (BeansException ex) {
  79. // Explicitly remove instance from singleton cache: It might have been put there
  80. // eagerly by the creation process, to allow for circular reference resolution.
  81. // Also remove any beans that received a temporary reference to the bean.
  82. destroySingleton(beanName);
  83. throw ex;
  84. }
  85. });
  86. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  87. }
  88. ......
  89. }

先去缓存中获取bean 不管是getBean方法还是spring初始化的时候都是使用这个方法
就是都是先从缓存(map)中获取bean 源码如下:

  1. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  2. Object singletonObject = this.singletonObjects.get(beanName);
  3. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  4. synchronized (this.singletonObjects) {
  5. singletonObject = this.earlySingletonObjects.get(beanName);
  6. if (singletonObject == null && allowEarlyReference) {
  7. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  8. if (singletonFactory != null) {
  9. singletonObject = singletonFactory.getObject();
  10. this.earlySingletonObjects.put(beanName, singletonObject);
  11. this.singletonFactories.remove(beanName);
  12. }
  13. }
  14. }
  15. }
  16. return singletonObject;
  17. }

首先看到的是从cache中获取这个单例的bean,这个缓存就是singletonObjects。如果获取不到,并且对象正在创建中,就再从二级缓存earlySingletonObjects中获取。如果还是获取不到且允许singletonFactories通过getObject()获取,就从三级缓存singletonFactory.getObject()(三级缓存)获取,如果获取到了则:从singletonFactories中移除,并放入earlySingletonObjects中。其实也就是从三级缓存移动到了二级缓存。

如果bean没有生产,通过doGetBean 内部的下面的方法getSingleton 实例化一个bean对象,getSingleton获取bean对象后就会存储到缓存中
getSingleton —> addSingleton 方法

  1. protected void addSingleton(String beanName, Object singletonObject) {
  2. synchronized (this.singletonObjects) {
  3. this.singletonObjects.put(beanName, singletonObject);
  4. this.singletonFactories.remove(beanName);
  5. this.earlySingletonObjects.remove(beanName);
  6. this.registeredSingletons.add(beanName);
  7. }
  8. }

初始化第一步的时候,会把对象放到三级缓存,等下一个对象循环引用的时候变成二级缓存,然后生成bean的时候,把三级和二级全部删除。

再实例化的时候 会先获取bean的RootBeanDefinition 这个RootBeanDefinition 也很重要(以后单独讲解),这里就是单纯的理解bean初始换的过程中会把bean的信息列入class ,name,params,singleton等等,很多信息都分装到一个对象,然后存储在缓存中

  1. if (mbd.isSingleton()) {
  2. sharedInstance = getSingleton(beanName, () -> {
  3. try {
  4. return createBean(beanName, mbd, args);
  5. }
  6. catch (BeansException ex) {
  7. // Explicitly remove instance from singleton cache: It might have been put there
  8. // eagerly by the creation process, to allow for circular reference resolution.
  9. // Also remove any beans that received a temporary reference to the bean.
  10. destroySingleton(beanName);
  11. throw ex;
  12. }
  13. });
  14. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  15. }

进入getSingleton

  1. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(beanName, "Bean name must not be null");
  3. synchronized (this.singletonObjects) {
  4. Object singletonObject = this.singletonObjects.get(beanName);
  5. if (singletonObject == null) {
  6. if (this.singletonsCurrentlyInDestruction) {
  7. throw new BeanCreationNotAllowedException(beanName,
  8. "Singleton bean creation not allowed while singletons of this factory are in destruction " +
  9. "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
  10. }
  11. if (logger.isDebugEnabled()) {
  12. logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
  13. }
  14. beforeSingletonCreation(beanName);
  15. boolean newSingleton = false;
  16. boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
  17. if (recordSuppressedExceptions) {
  18. this.suppressedExceptions = new LinkedHashSet<>();
  19. }
  20. try {
  21. singletonObject = singletonFactory.getObject();
  22. newSingleton = true;
  23. }
  24. catch (IllegalStateException ex) {
  25. // Has the singleton object implicitly appeared in the meantime ->
  26. // if yes, proceed with it since the exception indicates that state.
  27. singletonObject = this.singletonObjects.get(beanName);
  28. if (singletonObject == null) {
  29. throw ex;
  30. }
  31. }
  32. catch (BeanCreationException ex) {
  33. if (recordSuppressedExceptions) {
  34. for (Exception suppressedException : this.suppressedExceptions) {
  35. ex.addRelatedCause(suppressedException);
  36. }
  37. }
  38. throw ex;
  39. }
  40. finally {
  41. if (recordSuppressedExceptions) {
  42. this.suppressedExceptions = null;
  43. }
  44. afterSingletonCreation(beanName);
  45. }
  46. if (newSingleton) {
  47. addSingleton(beanName, singletonObject);
  48. }
  49. }
  50. return singletonObject;
  51. }
  52. }

代码太长 看重点,就是 singletonObject = singletonFactory.getObject(); 这行代码获取了bean的实例,这个是jdk1.8的方法引用语法(ps:要想看懂spring 对jdk1.8要有了解,并且熟悉常用设计模式),这个方法其实就是调用 getSingleton 的 createBean(beanName, mbd, args); 这个方法。

进入createBean(beanName, mbd, args);

  1. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. if (logger.isTraceEnabled()) {
  4. logger.trace("Creating instance of bean '" + beanName + "'");
  5. }
  6. RootBeanDefinition mbdToUse = mbd;
  7. // Make sure bean class is actually resolved at this point, and
  8. // clone the bean definition in case of a dynamically resolved Class
  9. // which cannot be stored in the shared merged bean definition.
  10. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  11. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  12. mbdToUse = new RootBeanDefinition(mbd);
  13. mbdToUse.setBeanClass(resolvedClass);
  14. }
  15. // Prepare method overrides.
  16. try {
  17. mbdToUse.prepareMethodOverrides();
  18. }
  19. catch (BeanDefinitionValidationException ex) {
  20. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  21. beanName, "Validation of method overrides failed", ex);
  22. }
  23. try {
  24. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  25. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  26. if (bean != null) {
  27. return bean;
  28. }
  29. }
  30. catch (Throwable ex) {
  31. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  32. "BeanPostProcessor before instantiation of bean failed", ex);
  33. }
  34. try {
  35. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  36. if (logger.isTraceEnabled()) {
  37. logger.trace("Finished creating instance of bean '" + beanName + "'");
  38. }
  39. return beanInstance;
  40. }
  41. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  42. // A previously detected exception with proper bean creation context already,
  43. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  44. throw ex;
  45. }
  46. catch (Throwable ex) {
  47. throw new BeanCreationException(
  48. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  49. }
  50. }

看重点,就是在Object beanInstance = doCreateBean(beanName, mbdToUse, args); 这个方法内部产生了bean,

进入doCreateBean 内部

  1. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. BeanWrapper instanceWrapper = null;
  5. if (mbd.isSingleton()) {
  6. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  7. }
  8. if (instanceWrapper == null) {
  9. instanceWrapper = createBeanInstance(beanName, mbd, args);
  10. }
  11. final Object bean = instanceWrapper.getWrappedInstance();
  12. Class<?> beanType = instanceWrapper.getWrappedClass();
  13. if (beanType != NullBean.class) {
  14. mbd.resolvedTargetType = beanType;
  15. }
  16. // Allow post-processors to modify the merged bean definition.
  17. synchronized (mbd.postProcessingLock) {
  18. if (!mbd.postProcessed) {
  19. try {
  20. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  21. }
  22. catch (Throwable ex) {
  23. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  24. "Post-processing of merged bean definition failed", ex);
  25. }
  26. mbd.postProcessed = true;
  27. }
  28. }
  29. // Eagerly cache singletons to be able to resolve circular references
  30. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  31. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  32. isSingletonCurrentlyInCreation(beanName));
  33. if (earlySingletonExposure) {
  34. if (logger.isTraceEnabled()) {
  35. logger.trace("Eagerly caching bean '" + beanName +
  36. "' to allow for resolving potential circular references");
  37. }
  38. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  39. }
  40. // Initialize the bean instance.
  41. Object exposedObject = bean;
  42. try {
  43. populateBean(beanName, mbd, instanceWrapper);
  44. exposedObject = initializeBean(beanName, exposedObject, mbd);
  45. }
  46. catch (Throwable ex) {
  47. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  48. throw (BeanCreationException) ex;
  49. }
  50. else {
  51. throw new BeanCreationException(
  52. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  53. }
  54. }
  55. if (earlySingletonExposure) {
  56. Object earlySingletonReference = getSingleton(beanName, false);
  57. if (earlySingletonReference != null) {
  58. if (exposedObject == bean) {
  59. exposedObject = earlySingletonReference;
  60. }
  61. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  62. String[] dependentBeans = getDependentBeans(beanName);
  63. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  64. for (String dependentBean : dependentBeans) {
  65. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  66. actualDependentBeans.add(dependentBean);
  67. }
  68. }
  69. if (!actualDependentBeans.isEmpty()) {
  70. throw new BeanCurrentlyInCreationException(beanName,
  71. "Bean with name '" + beanName + "' has been injected into other beans [" +
  72. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  73. "] in its raw version as part of a circular reference, but has eventually been " +
  74. "wrapped. This means that said other beans do not use the final version of the " +
  75. "bean. This is often the result of over-eager type matching - consider using " +
  76. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
  77. }
  78. }
  79. }
  80. }
  81. // Register bean as disposable.
  82. try {
  83. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  84. }
  85. catch (BeanDefinitionValidationException ex) {
  86. throw new BeanCreationException(
  87. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  88. }
  89. return exposedObject;
  90. }

就是 instanceWrapper = createBeanInstance(beanName, mbd, args); 这个方法实例化了bean对象

进入createBeanInstance 方法

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

直接进入重点 instantiateBean 这个方法

进入instantiateBean

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                                                         getInstantiationStrategy().instantiate(mbd, beanName, parent),
                                                         getAccessControlContext());
        }
        else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}

直接进入beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); 这个方法的 instantiate方法

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        // Don't override the class with CGLIB if no overrides.
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    final Class<?> clazz = bd.getBeanClass();
                    if (clazz.isInterface()) {
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(
                                    (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                        }
                        else {
                            constructorToUse = clazz.getDeclaredConstructor();
                        }
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    }
                    catch (Throwable ex) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                    }
                }
            }
            return BeanUtils.instantiateClass(constructorToUse);
        }
        else {
            // Must generate CGLIB subclass.
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }

可以看到是调用BeanUtils.instantiateClass(constructorToUse); 这个方法返回了 bean对象。

进入instantiateClass

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    Assert.notNull(ctor, "Constructor must not be null");
    try {
        ReflectionUtils.makeAccessible(ctor);
        if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
            return KotlinDelegate.instantiateClass(ctor, args);
        }
        else {
            Class<?>[] parameterTypes = ctor.getParameterTypes();
            Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
            Object[] argsWithDefaultValues = new Object[args.length];
            for (int i = 0 ; i < args.length; i++) {
                if (args[i] == null) {
                    Class<?> parameterType = parameterTypes[i];
                    argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
                }
                else {
                    argsWithDefaultValues[i] = args[i];
                }
            }
            return ctor.newInstance(argsWithDefaultValues);
        }
    }
    catch (InstantiationException ex) {
        throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
    }
    catch (IllegalAccessException ex) {
        throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
    }
    catch (IllegalArgumentException ex) {
        throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
    }
    catch (InvocationTargetException ex) {
        throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
    }
}

return ctor.newInstance(argsWithDefaultValues); 这个就是通过反射来实例化bean对象。

这里先解释一下三级缓存的问题,使用三级缓存,解决了循环依赖的问题,具体原理如下。
singletonFactories : 单例对象工厂的cache
earlySingletonObjects :提前暴光的单例对象的Cache
singletonObjects:单例对象的cache

从上面三级缓存的分析,我们可以知道,Spring解决循环依赖的诀窍就在于singletonFactories这个三级cache。这个cache的类型是ObjectFactory。这里就是解决循环依赖的关键,发生在createBeanInstance之后,也就是说单例对象此时已经被创建出来(调用了构造器)。这个对象已经被生产出来了,虽然还不完美(还没有进行初始化的第二步和第三步),但是已经能被人认出来了(根据对象引用能定位到堆中的对象),所以Spring此时将这个对象提前曝光出来让大家认识,让大家使用。

这样做有什么好处呢?让我们来分析一下“A的某个field或者setter依赖了B的实例对象,同时B的某个field或者setter依赖了A的实例对象”这种循环依赖的情况。A首先完成了初始化的第一步,并且将自己提前曝光到singletonFactories中,此时进行初始化的第二步,发现自己依赖对象B,此时就尝试去get(B),发现B还没有被create,所以走create流程,B在初始化第一步的时候发现自己依赖了对象A,于是尝试get(A),尝试一级缓存singletonObjects(肯定没有,因为A还没初始化完全),尝试二级缓存earlySingletonObjects(也没有),尝试三级缓存singletonFactories,由于A通过ObjectFactory将自己提前曝光了,所以B能够通过ObjectFactory.getObject拿到A对象(虽然A还没有初始化完全,但是总比没有好呀),B拿到A对象后顺利完成了初始化阶段1、2、3,完全初始化之后将自己放入到一级缓存singletonObjects中。此时返回A中,A此时能拿到B的对象顺利完成自己的初始化阶段2、3,最终A也完成了初始化,进去了一级缓存singletonObjects中,而且更加幸运的是,由于B拿到了A的对象引用,所以B现在hold住的A对象完成了初始化。

原理图:
image.png

总结:初始化bean的大体流程就是这样,其中涉及很多重要的方法,以后会单独详解。