Spring源码解析之-AbstractAutowireCapableBeanFactory#initializeBean详解

一、介绍

AbstractAutowireCapableBeanFactory 里面的方法比较多, 这里单独分析initializeBean 方法。

二、initializeBean 分析

2.1 initializeBean 流程图和步骤

在这里插入图片描述

主要步骤如下:

  1. 调用invokeAwareMethods 方法,对 Aware 各种类型进行赋值,暴露出去,供以后使用
  2. 运行 BeanPostProcessor 的前置方法:postProcessBeforeInitialization
  3. 运行InitializingBean 的 afterPropertiesSet 方法和 自定义的init Method
  4. 运行BeanPostProcessor 的后置方法:postProcessAfterInitialization
  5. 返回

2.2 源码分析

2.2.1 initializeBean方法

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        // 调用 AwareMethods 方法,判断 Bean 是否实现 Aware 相关接口,提供对应类型的数据 
        // 这里只有三种类型的Aware:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
        // 其实在下面的 初始化前置处理中还有 额外的比较全面的一些 Aware 进行完善
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		
		if (mbd == null || !mbd.isSynthetic()) {
		   //如果bean 是系统自定义的(不是应用程序定义的),就运行BeanPostProcessor 的前置方法:postProcessBeforeInitialization 
		   // 对应的详细方法 在下面解释,这里主要就是 一些
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
		   // 这里 开始校验 Bean  是否实现了InitializingBean 类, 或者自定义了 init 方法需要运行
		   // 详细分析在下方具体方法里面
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
		//  这里是调用后置处理器
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
	

2.2.2 invokeAwareMethods 方法

   /**
      *如果Bean实现了Aware 接口,就会将对应类型的数据 提供出去 ,这里一共三种:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
      * BeanNameAware==>beanName
      * BeanClassLoaderAware ==>BeanClassLoader
      * BeanFactoryAware ==>BeanFactory
    **/
	private void invokeAwareMethods(String beanName, Object bean) {

		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}

2.2.3 applyBeanPostProcessorsBeforeInitialization方法

这里主要就是 遍历运行 BeanPostProcessor 的前置处理方法postProcessBeforeInitialization,

@Override
	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {
 
        // 这里会拿到比较多的 实现了 BeanPostProcessor 的子类列表, 有自定义的,有系统定义的
        // 系统提供的实现了的子类有4个(如下图)
        // 例如: ApplicationContextAwareProcessor 的 postProcessBeforeInitialization 就是 对Aware 的其他类型进行补充完善
        //WebApplicationContextServletContextAwareProcessor 就是对ServletContextAware 进行提供对应的数据
        //ConfigurationClassPostProcessor#ImportAwareBeanPostProcessor 就是对ImportAware类型进行相关操作
		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessBeforeInitialization(result, beanName);
           
             // 这里一定要注意,如果 有一个返回null ,就停止后续的 处理了
             // 一般都是 返回 bean ,后续自己封装的时候也要注意了,这个比较重要 
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

在这里插入图片描述
ApplicationContextAwareProcessor 的 postProcessBeforeInitialization 方法里面 核心处理代码:
在这里插入图片描述

2.2.4 invokeInitMethods方法

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {

// 判断是否 实现了 InitializingBean 接口,如果实现了InitializingBean,就运行对应的afterPropertiesSet
		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isTraceEnabled()) {
				logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
						((InitializingBean) bean).afterPropertiesSet();
						return null;
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

 // 如果这里指定了 自定义 的 init method 
 // 这里要注意, 如果指定了init method , 那就不能InitializingBean 类型
 //或者 不能 和 afterPropertiesSet 同名 ,不然不运行
 // 这个 接口 是在 @PostConstruct之后执行的,@PostConstruct 会把这个接口放入到 externallyManagedInitMethods里面
		if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
					// 反射调用 自定义方法
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一直打铁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值