SpringBean生命周期

  1. AbstractApplicationContext中的refresh()方法,其中核心方法有两个registerBeanPostProcessors(beanFactory)和finshBeanFactoryInitialization(beanFactory)(实例化所有剩余的非懒加载的Singletions)。finshBeanFactoryInitialization(beanFactory)→beanFactory.preInstantiateSingletions()→DefaultListableBeanFactory.java中getBean(beanName)→AbstractBeanFactory.java中doGetBean(beanName, null, null, false)方法。
  2. AbstractBeanFactory.java中的doGetBean方法会执行DefaultSingletionBeanRegistry.java中getSingletons(beanName, true)方法
  1. protected Object getSingleton(String beanName, boolean allowEarlyReference) {
  2. // Quick check for existing instance without full singleton lock
  3. Object singletonObject = this.singletonObjects.get(beanName);
  4. if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
  5. singletonObject = this.earlySingletonObjects.get(beanName);
  6. if (singletonObject == null && allowEarlyReference) {
  7. synchronized (this.singletonObjects) {
  8. // Consistent creation of early reference within full singleton lock
  9. singletonObject = this.singletonObjects.get(beanName);
  10. if (singletonObject == null) {
  11. singletonObject = this.earlySingletonObjects.get(beanName);
  12. if (singletonObject == null) {
  13. ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
  14. if (singletonFactory != null) {
  15. singletonObject = singletonFactory.getObject();
  16. this.earlySingletonObjects.put(beanName, singletonObject);
  17. this.singletonFactories.remove(beanName);
  18. }
  19. }
  20. }
  21. }
  22. }
  23. }
  24. return singletonObject;
  25. }
  1. 第一次创建时,一二三级缓存都为null,继续执行AbstractBeanFactory的doGetBean方法,会调用DefaultListableBeanFactory中的重载方法getSingletions(beanName, ObjectFactory<?> singletonFactory)方法。
  2. 该方法中有四个关键步骤
    • 步骤A:beforeSingletonCreation(beanName),判断该bean是否在创建中,如果不在则将该bean放入SingletonCurrentlyInCreation的Set集合中。
    • 步骤B:执行singletonFactory.getObject()方法,获取对象(原始对象或代理对象)。
    • 步骤C:afterSingletonCreation(beanName),将该bean从正在创建的SingletonCurrentlyInCreation的Set集合中移除。
    • 步骤D:将对象放入单例池(SingletonObjects),并从二三级缓存中移除。
  3. 其中singletonFactory.getObject()方法中,会执行AbstractAutowireCapableBeanFactory中的doCreateBean()方法。
    • 该方法会执行addSingleonFactory(beanName, ()->getEarlyBeanReference(beanName, RootBeanDefinition, bean))。即将beanName、RootBeanDefinition和bean对象放入三级缓存中。
    • populateBean(beanName, RootBeanDefinition, bean) // 设置bean的属性
    • initializeBean(beanName, bean, RootBeanDefinition) // 初始化bean
      • initializeBean方法中分别执行invokeAwareMethods方法(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware)
      • 获取全部的BeanPostProcessor,执行postProcessBeforeInitialization方法
      • 执行invokeInitMethods(),如果实现了InitializingBean,执行afterPropertiesSet()方法,如果配置了initMethod方法,则执行initMethod方法
      • 执行BeanPostProcessor的postProcessAfterInitialization方法,即AbstractAutoProxyCreator中的执行BeanPostProcessor的postProcessAfterInitialization方法。先去earlyProxyReference的HashMap中判断是否提前进行了aop,wrapIfNecessary方法,生成代理对象。
  1. protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(singletonFactory, "Singleton factory must not be null");
  3. synchronized (this.singletonObjects) {
  4. if (!this.singletonObjects.containsKey(beanName)) {
  5. this.singletonFactories.put(beanName, singletonFactory);
  6. this.earlySingletonObjects.remove(beanName);
  7. this.registeredSingletons.add(beanName);
  8. }
  9. }
  10. }
  1. 如果是循环依赖,会去二级缓存(earlySingletonObjects)中找对象,没有的话会去三级缓存(singletonFacotries)中获取。会执行getEarlyBeanReference()方法,将该对象放入earlyProxyReferenceHashMap中,并生成代理对象。

ArrayList源码分析

add(E e)

  1. public boolean add(E e) {
  2. ensureCapacityInternal(size + 1); // Increments modCount!!
  3. elementData[size++] = e;
  4. return true;
  5. }

ensureCapacityInternal(size+1)

  1. // 数组内部容量检查
  2. private void ensureCapacityInternal(int minCapacity) {
  3. // 判断是否为空数组
  4. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  5. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  6. }
  7. ensureExplicitCapacity(minCapacity);
  8. }
  9. private void ensureExplicitCapacity(int minCapacity) {
  10. modCount++;
  11. // 最小容量>数组缓冲区长度
  12. if (minCapacity - elementData.length > 0)
  13. // 扩容
  14. grow(minCapacity);
  15. }
  16. private void grow(int minCapacity) {
  17. // 获取当前数组长度
  18. int oldCapacity = elementData.length;
  19. // 扩容,默认扩容1.5倍
  20. int newCapacity = oldCapacity + (oldCapacity >> 1);
  21. if (newCapacity - minCapacity < 0)
  22. newCapacity = minCapacity;
  23. // 如果扩容后的容量大于临界值,则进行大容量分配
  24. if (newCapacity - MAX_ARRAY_SIZE > 0)
  25. newCapacity = hugeCapacity(minCapacity);
  26. // minCapacity is usually close to size, so this is a win:
  27. // 新的数组容量大小已经确定,就复制数组,改变容量大小
  28. elementData = Arrays.copyOf(elementData, newCapacity);
  29. }
  30. private static int hugeCapacity(int minCapacity) {
  31. if (minCapacity < 0) // overflow
  32. throw new OutOfMemoryError();
  33. return (minCapacity > MAX_ARRAY_SIZE) ?
  34. Integer.MAX_VALUE :
  35. MAX_ARRAY_SIZE;
  36. }

我们调用add(e)方法时,函数调用过程如下:
函数调用流程图.png
remove(Object o)

  1. // 删除ArrayList指定位置的元素
  2. public E remove(int index) {
  3. RangeCheck(index);
  4. modCount++;
  5. E oldValue = (E) elementData[index];
  6. int numMoved = size - index - 1;
  7. if (numMoved > 0)
  8. System.arraycopy(elementData, index+1, elementData, index,
  9. numMoved);
  10. elementData[--size] = null; // Let gc do its work
  11. return oldValue;
  12. }
  13. // 删除ArrayList的指定元素
  14. public boolean remove(Object o) {
  15. if (o == null) {
  16. for (int index = 0; index < size; index++)
  17. if (elementData[index] == null) {
  18. fastRemove(index);
  19. return true;
  20. }
  21. } else {
  22. for (int index = 0; index < size; index++)
  23. if (o.equals(elementData[index])) {
  24. fastRemove(index);
  25. return true;
  26. }
  27. }
  28. return false;
  29. }
  30. // 快速删除第index个元素
  31. private void fastRemove(int index) {
  32. modCount++;
  33. int numMoved = size - index - 1;
  34. // 从"index+1"开始,用后面的元素替换前面的元素。
  35. if (numMoved > 0)
  36. System.arraycopy(elementData, index+1, elementData, index,
  37. numMoved);
  38. // 将最后一个元素设为null
  39. elementData[--size] = null; // Let gc do its work
  40. }
  41. // 删除元素
  42. public boolean remove(Object o) {
  43. if (o == null) {
  44. for (int index = 0; index < size; index++)
  45. if (elementData[index] == null) {
  46. fastRemove(index);
  47. return true;
  48. }
  49. } else {
  50. // 便利ArrayList,找到“元素o”,则删除,并返回true。
  51. for (int index = 0; index < size; index++)
  52. if (o.equals(elementData[index])) {
  53. fastRemove(index);
  54. return true;
  55. }
  56. }
  57. return false;
  58. }
  59. /**
  60. * 用src数组srcPos索引(包括该索引)元素值及其后面元素值,覆盖到
  61. * dest数组destPos索引(包括该索引)位置。
  62. */
  63. public static native void arraycopy(Object src, int srcPos,
  64. Object dest, int destPos,
  65. int length);

clear()

  1. /**
  2. * 移除list中的所有元素,这个list表将在调用之后置空
  3. * - 它会将数组缓冲区所以元素置为 null
  4. * - 清空后,我们直接打印 list,却只会看见一个 [], 而不是 [null, null, ….] ==> toString() 和 迭代器进行了处理
  5. */
  6. public void clear() {
  7. modCount++;
  8. // clear to let GC do its work
  9. for (int i = 0; i < size; i++)
  10. elementData[i] = null;
  11. size = 0;
  12. }