SpringBean实例化之bean对象的实例化过程解析

前言

SpringBean实例化之bean对象创建前的验证工作一文中我们已经了解了bean对象的实例化前的验证工作,本文开始研究bean对象的实例化过程

初始化单个单例bean的核心步骤

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// 用BeanWrapper来持有创建出来的Bean对象
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			//如果是单例的话,则先把缓存中的同名bean清除(同名的)
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		//实际创建的交给createBeanInstance来完成,
		//bean的生成,这里会使用默认的类生成器,包装成BeanWrapperImpl类,为了下面的populateBean方法的属性注入做准备
		if (instanceWrapper == null) {
		     //1、调用构造器,底层比较复杂。可以理解就是Spring调用我们定义的构造器
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		//从BeanWrapper对象包装器中获取当前bean对象
		final Object bean = instanceWrapper.getWrappedInstance();
		//获取当前bean的class
		Class<?> beanType = instanceWrapper.getWrappedClass();
		//如果不是NullBean,则将resolvedTargetType 属性设置为当前的WrappedClass
		if (beanType != NullBean.class) {
		    //把当前RootBeanDefinition的class对象
			mbd.resolvedTargetType = beanType;
		}

		//允许后处理器修改合并的bean定义。
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
			
					// 主要是处理@PostConstruct,@Autowire,@Value,@Resource,@PreDestory等这些注解。
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		//如果当前bean是单例,且支持循环依赖,且当前bean正在创建,通过往singletonFactories添加一个objectFactory,这样后期如果有其他bean依赖该bean 可以从singletonFactories获取到bean
		//getEarlyBeanReference可以对返回的bean进行修改,这边目前除了可能会返回动态代理对象 其他的都是直接返回bean
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			// 这里面主要是解决循环引用问题~~~~~~~~~借助了这个工厂
			//这里主要是调用处理器:SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference方法去寻找到前期的Bean们(若存在这种处理器的话)
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// 这个Obj,就是最终要返回的对象了
		Object exposedObject = bean;
		try {
			// 这又是非常非常重要的一步:给已经初始化的属性们赋值===================对bean进行填充,在这里面完成依赖注入的相关内容
			// 啥都不说了,看下面的详解吧
			populateBean(beanName, mbd, instanceWrapper);
			//完成属性依赖注入后,进一步初始化Bean  具体进行了以下操作:
			//若实现了BeanNameAware, BeanClassLoaderAware,BeanFactoryAwareAware等接口,则注入相关对象
			//遍历后置处理器,调用实现的postProcessBeforeInitialization方法,
			//如果实现了initialzingBean,调用实现的 afterPropertiesSet()
			//如果配置了init-mothod,调用相应的init方法
			//遍历后置处理器,调用实现的postProcessAfterInitialization

			// 关于populateBean和initializeBean的详解,下贴出了博文链接参考~~~~~~
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}
		//如果earlySingletonExposure为true,尝试从缓存获取该bean(一般存放在singletonFactories对象通过调用getObject 把对象存入earlySingletonObjects),
		// 分别从singletonObjects和earlySingletonObjects获取对象   这里依然是处理循环依赖相关问题的

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				//如果获取到对象了
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException("");
					}
				}
			}
		}
		// 如果有需要,就注册DisposableBean,这样Bean销毁的时候此种后置处理器也会生效了
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

1、调用构造器
2、处理@PostConstruct,@Autowire,@Value,@Resource,@PreDestory等这些注解
3、属性们赋值
4、Bean的初始化

一、调用构造器

使用适当的实例化策略工厂方法、构造函数自动连线或简单实例化为指定bean创建新实例。

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// 确保bean类在这一点上被实际解析。
		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);
			}
		}

		// 由后置处理器决定调用那个构造器
		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);
	}

二、执行MergedBeanDefinitionPostProcessor后置处理器

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

三、属性赋值

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

	
		boolean continueWithPropertyPopulation = true;
        //1、执行InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation   
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}

		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// 如果适用,根据名称添加基于autowire的特性值。
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			//如果适用,根据类型添加基于autowire的特性值。
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

四、对象初始化

1、实际应用

springBean实例化对象的初始化方法和销毁方法,其实现方法有3种

注意:在懒加载条件下,容器是不会主动调用bena的初始化方法和销毁方法

1、使用@Bean属性

@Configuration
public class CarFactory {
     
     @Bean(initMethod="init",destroyMethod="destory",name="car")
     public Car car(){
           return new Car();
     } 
}

2、使用@PostConstruct(标识这个方法是初始化方法) @PreDestroy(标识这个方法是销毁方法)

public class Car {
     
     @PreDestroy
     public void destroy() throws Exception {
           System.out.println("destory....");
     }

     @PostConstruct
     public void init() throws Exception {
           System.out.println("init....");
     }
}

3、让bean实现InitializingBean和DisposableBean接口

1、InitializingBean

public interface InitializingBean {
     void afterPropertiesSet() throws Exception;//bean在初始化时调用
}

2、DisposableBean

public interface DisposableBean {
     void destroy() throws Exception;//bean在销毁时调用
}

2、源码解析

1、 执行后置处理器BeanPostProcessorpostProcessBeforeInitialization(Object bean, String beanName)方法
2、调用InitializingBean接口初始化 (如果配置了method-init,则调用其方法初始化 )
3、 执行后置处理器BeanPostProcessorpostProcessAfterInitialization方法

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {

		// 第一步:先执行所有的AwareMethods,具体如下代码,比较简单
		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()) {
			// 执行所有的BeanPostProcessor#postProcessBeforeInitialization  初始化之前的处理器方法
			// 规则:只要谁反回了null,后面的就都不要执行了
			// 这里面实现postProcessBeforeInitialization 的处理器就很多了,有很多对Aware进行了扩展的,具体如下面的具体介绍
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			//这里就开始执行afterPropertiesSet(实现了InitializingBean接口)方法和initMethod
			// 备注:这里initMethod方法的名称不能是afterPropertiesSet,并且这个类不是 InitializingBean类型才会调用,需要特别注意。
			//(然后该方法只有方法名,所以肯定是反射调用,效率稍微低那么一丢丢)

			// 由此可以见,实现这个接口的初始化方法,是在标注形如@PostConstruct之后执行的
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException();
		}
		if (mbd == null || !mbd.isSynthetic()) {
			// 整个Bean都初始化完成了,就执行后置处理器的这个方法postProcessAfterInitialization
			// 如果谁反悔了null,后面的处理器都不会再执行了
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

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

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			
			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) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}

你可能感兴趣的:(Spring-IOC)