spring源码执行bean的init方法 initializeBean

21 篇文章 1 订阅
11 篇文章 0 订阅

前篇文章传送门
前两篇了解了bean的属性性赋值,这个过程如果字段是引用类型的对象,那么spring会去工厂中查找,如果查找不到,再去执行工厂创建bean的那套流程,现在属性赋值完成了后,接下来开始执行init方法了。
那么执行init方法前后会做哪些事情呢?

  1. invokeAwareMethods Aware接口是做什么的?
  2. postProcessBeforeInitialization 作用是什么?
  3. 什么时候执行init方法?
  4. applyBeanPostProcessorsAfterInitialization 作用是什么?
initializeBean 初始化bean
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
	// 安全管理器不用考虑
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
			invokeAwareMethods(beanName, bean);
			return null;
		}, getAccessControlContext());
	}else {
		// 执行Aware接口方法
		invokeAwareMethods(beanName, bean);
	}
	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		// 执行BPP的Before方法
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}
	try {
		// 执行初始化方法
		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()) {
		// 执行BPP的After方法
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}
	// 返回创建好的对象(可能是代理对象)
	return wrappedBean;
}
invokeAwareMethods 执行Aware方法

Aware的作用是什么呢?就是注入当前资源,比如BeanFactoryAware,就是注入BeanFactory,这个Aware工作中比较常用,如果咱们拿到BeanFactory之后可以做很多事情了

private void invokeAwareMethods(String beanName, Object bean) {
	// 执行BeanClassLoaderAware
	if (bean instanceof Aware) {
		if (bean instanceof BeanNameAware) {
			((BeanNameAware) bean).setBeanName(beanName);
		}
		// 执行BeanClassLoaderAware
		if (bean instanceof BeanClassLoaderAware) {
			ClassLoader bcl = getBeanClassLoader();
			if (bcl != null) {
				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
			}
		}
		// 执行BeanFactoryAware
		if (bean instanceof BeanFactoryAware) {
			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
		}
	}
}
applyBeanPostProcessorsBeforeInitialization 执行BPP的before方法

执行ImportAware、invokeInitMethods(注解@PostConstruct)等

// 执行postProcessBeforeInitialization
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)throws BeansException {

	Object result = existingBean;
	for (BeanPostProcessor processor : getBeanPostProcessors()) {
		// 执行before方法
		Object current = processor.postProcessBeforeInitialization(result, beanName);
		if (current == null) {
			return result;
		}
		result = current;
	}
	// 返回当前对象创建好的对象或者是before方法常见的别的对象
	return result;
}
invokeInitMethods 执行init方法

执行ImportAware、invokeInitMethods(注解@PostConstruct)等

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)throws Throwable {
	// 如果bean实现了 InitializingBean 那么执行afterPropertiesSet方法 springMVC就是执行这个方法进行初始化的
	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();
		}
	}

	if (mbd != null && bean.getClass() != NullBean.class) {
		// 如果bean定义信息中配置了init-method方法,那么执行
		String initMethodName = mbd.getInitMethodName();
		if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
			// 执行init (xml)
			// ReflectionUtils.makeAccessible(methodToInvoke);
			// methodToInvoke.invoke(bean);
			invokeCustomInitMethod(beanName, bean, mbd);
		}
	}
}
postProcessAfterInitialization 执行BPP的after方法

AOP动态代理就是在这里实现的,以后会继续一起学习…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值