上一篇分析了单实例bean创建过程中的属性赋值,接下来我们分析,单实例bean属性赋值之后的初始化**initializeBean()**

1. initializeBean()

  1. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  2. /*检查当前bean是否实现了aware接口,再具体判断实现的哪个aware接口,做一些赋能操作。*/
  3. invokeAwareMethods(beanName, bean);
  4. Object wrappedBean = bean;
  5. if (mbd == null || !mbd.isSynthetic()) {
  6. /*初始化之前,后置处理器的调用点*/
  7. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  8. }
  9. try {
  10. /*执行初始化方法*/
  11. invokeInitMethods(beanName, wrappedBean, mbd);
  12. }
  13. catch (Throwable ex) {
  14. throw new BeanCreationException(
  15. (mbd != null ? mbd.getResourceDescription() : null),
  16. beanName, "Invocation of init method failed", ex);
  17. }
  18. if (mbd == null || !mbd.isSynthetic()) {
  19. /*初始化后的后置处理器执行点*/
  20. /*典型应用:AOP的具体实现*/
  21. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  22. }
  23. return wrappedBean;
  24. }

在初始化之前,把当前bean实现的所有Aware接口都执行一遍。**invokeAwareMethods()**
在初始化之前,调用后置处理器。**applyBeanPostProcessorsBeforeInitialization()**
执行初始化逻辑。**invokeInitMethods()**
执行后置处理器的调用点,典型的实现其实就是AOP。**applyBeanPostProcessorsAfterInitialization()**
返回包装对象。

2.invokeAwareMethods()

  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. }

执行相关的Aware接口方法。

3.applyBeanPostProcessorsBeforeInitialization()

  1. @Override
  2. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  5. /*beanPostProcessor的执行逻辑*/
  6. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  7. Object current = processor.postProcessBeforeInitialization(result, beanName);
  8. if (current == null) {
  9. return result;
  10. }
  11. result = current;
  12. }
  13. return result;
  14. }

循环所有的后置处理器,执行前置方法,如果有一个返回结果为空,直接短路,后面的都不执行了。

4.invokeInitMethods()

  1. protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
  2. throws Throwable {
  3. /*如果是实现了InitializingBean接口*/
  4. boolean isInitializingBean = (bean instanceof InitializingBean);
  5. if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
  6. if (logger.isTraceEnabled()) {
  7. logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
  8. }
  9. /*执行afterPropertiesSet方法*/
  10. ((InitializingBean) bean).afterPropertiesSet();
  11. }
  12. if (mbd != null && bean.getClass() != NullBean.class) {
  13. /*判断重写init方法没?*/
  14. String initMethodName = mbd.getInitMethodName();
  15. if (StringUtils.hasLength(initMethodName) &&
  16. !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
  17. !mbd.isExternallyManagedInitMethod(initMethodName)) {
  18. /*执行重写的init方法*/
  19. invokeCustomInitMethod(beanName, bean, mbd);
  20. }
  21. }
  22. }

判断实现了**InitializingBean**接口的,执行里面的方法。
判断重写了初始化方法的,执行重写的方法。

4.1 invokeCustomInitMethod()

  1. protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd)
  2. throws Throwable {
  3. /*从bd获取init方法*/
  4. String initMethodName = mbd.getInitMethodName();
  5. Assert.state(initMethodName != null, "No init method set");
  6. /*
  7. * isNonPublicAccessAllowed 非公开访问
  8. *
  9. * 这里完成之后就会获取到通过init方法定义的方法对象。
  10. * */
  11. Method initMethod = (mbd.isNonPublicAccessAllowed() ?
  12. BeanUtils.findMethod(bean.getClass(), initMethodName) :
  13. ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
  14. /*如果init方法为空*/
  15. if (initMethod == null) {
  16. if (mbd.isEnforceInitMethod()) {
  17. throw new BeanDefinitionValidationException("Could not find an init method named '" +
  18. initMethodName + "' on bean with name '" + beanName + "'");
  19. }
  20. else {
  21. if (logger.isTraceEnabled()) {
  22. logger.trace("No default init method named '" + initMethodName +
  23. "' found on bean with name '" + beanName + "'");
  24. }
  25. // Ignore non-existent default lifecycle methods.
  26. return;
  27. }
  28. }
  29. if (logger.isTraceEnabled()) {
  30. logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
  31. }
  32. /*将init方法转换成接口层面获取的initMethod*/
  33. Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
  34. try {
  35. /*反射执行方法*/
  36. ReflectionUtils.makeAccessible(methodToInvoke);
  37. methodToInvoke.invoke(bean);
  38. }
  39. catch (InvocationTargetException ex) {
  40. throw ex.getTargetException();
  41. }
  42. }

经过一些列处理,反射调用初始化方法。

5.applyBeanPostProcessorsAfterInitialization()

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            /*注意:
            * 一旦某个后置处理器返回的结果为空
            * 就返回上一个后置处理器的结果,后面的后置处理器方法不在执行*/
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

初始化之后,遍历所有的后置处理器,执行后置处理器的后置方法,如果有一个返回结果是空,直接返回,后面的后置处理器都不执行了。

至此,整个ioc容器的刷新流程就都分析完了,重点就在于单实例bean的创建流程,首先会去**getBean() doGetBean() getSinglton() createBean() doCreateBean() populateBean() initializeBean()**。下一篇我们将会去分析Spring的三级缓存和循环依赖。