Spring Bean生命周期doCreateBean源码阅读

 

bean的生命周期的几个后置接口都是在这个方法里面调用,所以单独开一篇该方法的源码阅读

下面从两个点来阅读:

1.何时调用(只看容器启动)

2.梳理这个方法的流程(跟上一节对应上

先贴上源码:

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

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			// factoryBeanObjectCache:存的是beanName对应的FactoryBean.getObject()所返回的对象
			// factoryBeanInstanceCache:存的是beanName对应的FactoryBean实例对象
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}

		// 2、实例化
		if (instanceWrapper == null) {
			// 创建bean实例  new USerSerive()
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}

		// 原始对象
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					// 运行修改合并好了的BeanDefinition
					// 这里会查找@Autowired的注入点(InjectedElement),并把这些注入点添加到mbd的属性externallyManagedConfigMembers中
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		// 如果当前创建的是单例bean,并且允许循环依赖,并且还在创建过程中,那么则提早暴露
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			// 此时的bean还没有完成属性注入,是一个非常简单的对象
			// 构造一个对象工厂添加到singletonFactories中
			// 第四次调用后置处理器
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));  // AService
		}

		// Initialize the bean instance.
		// 对象已经暴露出去了
		Object exposedObject = bean;
		try {
			// 3、填充属性 @Autowired
			populateBean(beanName, mbd, instanceWrapper);  //

			// 4、 初始化 和 BeanPostProcessor 正常AOP  BeanPostProcessor
			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);
			}
		}

		if (earlySingletonExposure) {
			// 在解决循环依赖时,当AService的属性注入完了之后,从getSingleton中得到AService AOP之后的代理对象
			Object earlySingletonReference = getSingleton(beanName, false);  // earlySingletonObjects
			if (earlySingletonReference != null) {
				// 如果提前暴露的对象和经过了完整的生命周期后的对象相等,则把代理对象赋值给exposedObject
				// 最终会添加到singletonObjects中去
				if (exposedObject == bean) {  //
					exposedObject = earlySingletonReference;
				}
				// 如果提前暴露的对象和经过了完整的生命周期后的对象不相等
				// allowRawInjectionDespiteWrapping表示在循环依赖时,只能
				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()) {
						// AService的原始对象被注入给了其他bean,但是AService最后被包装了
						// 也就是说其他bean没有用到AService的最终版本
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

1.何时调用(只看容器启动)

咱们现在只看UserService 这个类的创建,其余的后续在分析。

还是一样,咱们打上条件断点:

启动测试代码:

由上面可以看到,先执行实例化的后置处理器TestInstantiationAwareBeanPostProcessor的前置方法,查看调用栈针可以看到是在创建AnnotationConfigApplicationContext时候在refresh()里

// Instantiate all remaining (non-lazy-init) singletons.
// 完成beanFactory的初始化(实例化非懒加载的单例bean)
finishBeanFactoryInitialization(beanFactory);
createBean()方法,源码如下:
@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		try {
			// 对通过XML定义的bean中的look-up方法进行预处理
			// 对于@Lookup注解标注的方法不在这里进行处理,@AutowiredAnnotationBeanPostProcessor会处理@Lookup注解
			// 不研究了
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			// 1、实例化前 null
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);  // 对象
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			// 创建bean   Spring自带的创建bean的方法
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

该方法也是抽象工厂类的方法:

简单分析下该方法的流程:

1.对传过来的RootBeanDefinition进行一些处理

2.然后调用实例化前的方法

3.最后去调用doCreateBean方法生成一个object 对象

所以UserService创建的时候会createBean()方法,然后按上面的流程调用到doCreateBean方法。

 

2.梳理这个方法doCreateBean的流程

		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			// factoryBeanObjectCache:存的是beanName对应的FactoryBean.getObject()所返回的对象
			// factoryBeanInstanceCache:存的是beanName对应的FactoryBean实例对象
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}

(1)判断是否单例,清除掉工厂缓存池factoryBeanInstanceCache的实例的包装器

 

// 2、实例化
		if (instanceWrapper == null) {
			// 创建bean实例  new USerSerive()
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}

(2)实例化:这里面会推断构造方法,如果没有就按无参构造方法实例

 

		// 原始对象
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					// 运行修改合并好了的BeanDefinition
					// 这里会查找@Autowired的注入点(InjectedElement),并把这些注入点添加到mbd的属性externallyManagedConfigMembers中
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

(3)这个点是接口MergedBeanDefinitionPostProcessor的扩展点:在BeanPostProcessor的基础上增加了在实例化和实例化后之间的扩展点,也是继承BeanPostProcessor接口。

接口源码:

public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {

	/**
	 * Post-process the given merged bean definition for the specified bean.
	 * @param beanDefinition the merged bean definition for the bean
	 * @param beanType the actual type of the managed bean instance
	 * @param beanName the name of the bean
	 * @see AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
	 */
	void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);

	/**
	 * A notification that the bean definition for the specified name has been reset,
	 * and that this post-processor should clear any metadata for the affected bean.
	 * <p>The default implementation is empty.
	 * @param beanName the name of the bean
	 * @since 5.1
	 * @see DefaultListableBeanFactory#resetBeanDefinition
	 */
	default void resetBeanDefinition(String beanName) {
	}

}
// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		// 如果当前创建的是单例bean,并且允许循环依赖,并且还在创建过程中,那么则提早暴露
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			// 此时的bean还没有完成属性注入,是一个非常简单的对象
			// 构造一个对象工厂添加到singletonFactories中
			// 第四次调用后置处理器
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));  // AService
		}

(4)这部分也是在实例化的一些操纵,设计到AbstractAutowireCapableBeanFactory的一些属性操做,总之为之后做准备(没有深入去了解)

 

// Initialize the bean instance.
		// 对象已经暴露出去了
		Object exposedObject = bean;
		try {
			// 3、填充属性 @Autowired
			populateBean(beanName, mbd, instanceWrapper);  //

			// 4、 初始化 和 BeanPostProcessor 正常AOP  BeanPostProcessor
			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);
			}
		}

(5)这部分就是属性填充和初始化了

populateBean(beanName, mbd, instanceWrapper);里面会调用实例化后InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation方法

// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		// 可以提供InstantiationAwareBeanPostProcessor,控制对象的属性注入
		// 我们可以自己写一个InstantiationAwareBeanPostProcessor,然后重写postProcessAfterInstantiation方法返回false,那么则不会进行属性填充了
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}

这里判断执行的该方法返回是True 和false 如果false 就直接结束,后续不再进行属性填充,反之就会去执行InstantiationAwareBeanPostProcessor.postProcessProperties方法。

属性填充完了,再看初始化initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)

	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			// 4.1、执行Aware
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 4.2、初始化前
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 4.3、初始化
			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()) {
			// 4.4、初始化后 AOP  ()
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
 
if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			// 4.1、执行Aware
			invokeAwareMethods(beanName, bean);
		}

进来就开始执行前置Aware:

BeanNameAware
BeanClassLoaderAware
BeanFactoryAware
Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 4.2、初始化前
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

然后初始化前的代码BeanPostProcessor.postProcessBeforeInitialization

首先AnnotationConfigApplicationContext.postProcessBeforeInitialization

	@Override
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
			return bean;
		}

		AccessControlContext acc = null;

		if (System.getSecurityManager() != null) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

执行了上一节后续的几个Aware

后续还有很多BeanPostProcessor的处理暂时不分析

最后执行我们自己的BeanPostProcessor.postProcessBeforeInitialization(跟排序有关,暂时没测试)

然后是初始化:

try {
			// 4.3、初始化
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}

这里面会执行InitializingBean.afterPropertiesSet方法;

最后是初始化后的BeanPostProcessor.postProcessAfterInitialization:

if (mbd == null || !mbd.isSynthetic()) {
			// 4.4、初始化后 AOP  ()
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

到这一不可以看到上一节的bean生命周期的流程都执行完了

 

(6)后面的暂时先不分析,循环依赖问题。

 

总结:

根据上一节的生命周期的内容分析createBean里面的doCreateBean内容。总而言之:

1.doCreateBean是在createBean后面调用的,在createBean方法会执行InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation

2.然后在执行doCreateBean方法,首先先实例化

3.然后在属性填充的那里首选会执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation

4.属性填充完,马上就开始初始化,进来就开始执行前置Aware:

BeanNameAware
BeanClassLoaderAware
BeanFactoryAware

5.利用AnnotationConfigApplicationContext.postProcessBeforeInitialization的前置方法执行后续的Aware,如果有

6.执行自己的BeanPostProcessor.postProcessBeforeInitialization(跟排序有关,暂时先这样分析)

7.初始化,这里面会执行InitializingBean.afterPropertiesSet方法;

8.最后是初始化后的BeanPostProcessor.postProcessAfterInitialization

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架提供了对Bean的生命周期管理。在Spring源码中,Bean的生命周期由两个关键接口定义:BeanFactory和BeanPostProcessor。 BeanFactory是Spring的核心接口之一,它负责管理所有的Bean,并负责实例化、配置和管理它们的整个生命周期BeanFactory接口定义了许多方法,如getBean()和registerBeanDefinition(),用于获取和注册Bean。 BeanPostProcessor是另一个重要的接口,它定义了在Bean初始化的不同阶段可以插入自定义逻辑的扩展点。通过实现BeanPostProcessor接口,开发人员可以在Bean的实例化、初始化和销毁等阶段插入自己的逻辑。BeanPostProcessor接口中定义了两个方法:postProcessBeforeInitialization()和postProcessAfterInitialization()。 在Spring源码中,Bean的生命周期主要涉及以下几个重要的类和方法: 1. DefaultListableBeanFactory类:此类实现了BeanFactory接口,是Spring容器的核心实现类之一。它负责读取Bean的定义信息,并根据这些定义信息创建和管理Bean。 2. AbstractAutowireCapableBeanFactory类:此类是DefaultListableBeanFactory的子类,它提供了Bean的自动装配功能。它包含了Bean的实例化、属性注入、初始化和销毁等关键步骤。 3. AnnotationConfigApplicationContext类:此类是通过注解配置来创建Spring容器的一种方式。它根据指定的配置类,扫描注解并完成Bean的初始化和管理。 4. BeanDefinition类:此类定义了Bean的配置信息,包括Bean的类名、属性值和依赖关系等。在Bean的生命周期中,BeanDefinition起到了重要的作用。 以上只是Spring Bean生命周期源码的一部分,如果你对Spring Bean生命周期源码感兴趣,建议你阅读Spring源码以获得更详细的了解。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值