【spring】创建Bean的方法:createBean源码分析

createBean简单介绍

  • 本文源码基于spring-framework-5.3.10。
  • 这个方法有Bean的一大半生命周期

createBean的核心流程

  • 实例化前:InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
  • 实例化:推断构造方法
  • 后置处理合并后的BeanDefinition:MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()
  • 实例化后:InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
  • 属性赋值,自动注入(@Autowired、@Resource、@Value):InstantiationAwareBeanPostProcessor.postProcessProperties()
  • 回调:Aware对象
  • 初始化前:BeanPostProcessor.postProcessBeforeInitialization()
  • 初始化
  • 初始化后:BeanPostProcessor.postProcessAfterInitialization()

源码分析

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

	// 日志打印
	if (logger.isTraceEnabled()) {
		logger.trace("Creating instance of bean '" + beanName + "'");
	}
	// 使用的BeanDefinition
	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.
	// 马上就要实例化Bean了,确保beanClass被加载了
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	// Bean被加载,并且当前BeanDefinition的beanClass属性不是class类型,并且对应的BeanNam不是Null
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		// 重新定义一个BeanDefinition。这里之前的BeanClass属性是字符串!
		mbdToUse = new RootBeanDefinition(mbd);
		// 把上面实例化的Bean设置进去
		mbdToUse.setBeanClass(resolvedClass);
	}

	// Prepare method overrides.
	// 这里主要处理@Lookup注解,进行方法的替代!
	try {
		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.
		// 实例化前
		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 {
		// spring本身的实例化
		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);
	}
}

确保Bean被加载的方法:resolveBeanClass源码分析

protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
		throws CannotLoadBeanClassException {

	try {
		// 校验当前BeanDefinition的beanClass属性是Bean的名字还是Bean的class信息:如果beanClass被加载了(beanClass的类型是class),直接返回
		if (mbd.hasBeanClass()) {
			return mbd.getBeanClass();
		}

		// 如果beanClass没有被加载,进行Bean的加载
		if (System.getSecurityManager() != null) {
			return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)
					() -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
		}
		else {
			return doResolveBeanClass(mbd, typesToMatch);
		}
	}
	catch (PrivilegedActionException pae) {
		ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
		throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
	}
	catch (ClassNotFoundException ex) {
		throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
	}
	catch (LinkageError err) {
		throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
	}
}

真正的创建方法:doResolveBeanClass源码分析

private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
		throws ClassNotFoundException {
	// 得到当前Bean的类加载器
	ClassLoader beanClassLoader = getBeanClassLoader();
	// 定义一个动态的类加载器。有临时类加载器用临时类加载器,没有临时类加载器用现在这个
	ClassLoader dynamicLoader = beanClassLoader;
	// 表示RootBeanDefinition的配置的bean类名需要重新被dynameicLoader加载的标记,默认不需要
	boolean freshResolve = false;

	// 进行类型匹配
	if (!ObjectUtils.isEmpty(typesToMatch)) {
		// When just doing type checks (i.e. not creating an actual instance yet),
		// use the specified temporary class loader (e.g. in a weaving scenario).
		// 一个临时的类加载器,用于类型的匹配校验
		ClassLoader tempClassLoader = getTempClassLoader();
		// 解析的值不一样,走下面的逻辑
		if (tempClassLoader != null) {
			// 吧当前的类加载器赋值给动态类加载器
			dynamicLoader = tempClassLoader;
			// 标记当前的RootBeanDefinition需要被dynamicLoader解析
			freshResolve = true;
			// 他是spring自定义的DecoratingClassLoader类加载器
			if (tempClassLoader instanceof DecoratingClassLoader) {
				// 类加载器强转
				DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
				// 类型匹配!
				for (Class<?> typeToMatch : typesToMatch) {
					dcl.excludeClass(typeToMatch.getName());
				}
			}
		}
	}

	// 获取className:beanClass是名称直接返回,是class返回class对应的Name
	String className = mbd.getBeanClassName();
	if (className != null) {
		// 解析Spring表达式,有可能直接返回了一个Class对象
		Object evaluated = evaluateBeanDefinitionString(className, mbd);
		// 表达式解析的类型不一致
		if (!className.equals(evaluated)) {
			// A dynamically resolved expression, supported as of 4.2...
			// 4.2支持动态的类型。能得到class类型直接返回
			if (evaluated instanceof Class) {
				return (Class<?>) evaluated;
			}
			// 得到的是字符串
			else if (evaluated instanceof String) {
				// BeanName赋值
				className = (String) evaluated;
				// 标记当前的RootBeanDefinition需要被dynamicLoader解析
				freshResolve = true;
			}
			else {
				// 除了class类型和字符串,其他的直接抛异常
				throw new IllegalStateException("Invalid class name expression result: " + evaluated);
			}
		}
		// 类没有被加载的时候,进行加载
		if (freshResolve) {
			// When resolving against a temporary class loader, exit early in order
			// to avoid storing the resolved Class in the bean definition.
			// 类加载器不能为空!
			if (dynamicLoader != null) {
				try {
					// 返回用dynamicLoader具体的类加载器加载类,得到class对象
					return dynamicLoader.loadClass(className);
				}
				catch (ClassNotFoundException ex) {
					if (logger.isTraceEnabled()) {
						logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
					}
				}
			}
			// 加载数组,String,基本类型
			return ClassUtils.forName(className, dynamicLoader);
		}
	}

	// Resolve regularly, caching the result in the BeanDefinition...
	// 定期解析,将结果缓存在BeanDefinition中。可以通过AbstractBeanDefinition#getBeanClass来获取缓存
	return mbd.resolveBeanClass(beanClassLoader);
}

创建Bean使用的类加载器信息

/**
 * 获取类加载器信息的方法
 */
public ClassLoader getBeanClassLoader() {
	return this.beanClassLoader;
}

// 使用的类加载器信息
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

/**
 * 初始化类加载器的方法
 */
public static ClassLoader getDefaultClassLoader() {
	ClassLoader cl = null;

	// 优先获取线程中的类加载器。通过Thread.currentThread().setContextClassLoader(cl)进行设置
	try {
		cl = Thread.currentThread().getContextClassLoader();
	}
	catch (Throwable ex) {
		// Cannot access thread context ClassLoader - falling back...
	}

	// 线程中类加载器为null的情况下,获取加载ClassUtils类的类加载器
	if (cl == null) {
		// No thread context class loader -> use class loader of this class.
		// 使用和ClassUtils相同的类加载器。简单理解就是和spring-core包放的位置有关系
		cl = ClassUtils.class.getClassLoader();
		if (cl == null) {
			// getClassLoader() returning null indicates the bootstrap ClassLoader
			// 加入ClassUtils是被Bootstrap类加载器加载的,则获取系统类加载器。(jre/lib目录下)
			try {
				cl = ClassLoader.getSystemClassLoader();
			}
			catch (Throwable ex) {
				// Cannot access system ClassLoader - oh well, maybe the caller can live with null...
			}
		}
	}
	return cl;
}

实例化前:resolveBeforeInstantiation源码分析

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
	Object bean = null;
	// 如果当前还没有进行实例化钱的操作
	if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
		// Make sure bean class is actually resolved at this point.
		// synthetic表示合成,如果某些Bean式合成的,那么则不会经过BeanPostProcessor的处理。并且他有实例化前的实现:。并且把所有的InstantiationAwareBeanPostProcessor、SmartInstantiationAwareBeanPostProcessor、DestructionAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor加入到BeanPostProcessorCache,判断加入后有没有InstantiationAwareBeanPostProcessor。
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			// 得到class类型
			Class<?> targetType = determineTargetType(beanName, mbd);
			// 得到的class类型不为null
			if (targetType != null) {
				// 循环调用每个postProcessBeforeInstantiation方法,直到有返回值(自己去实例化),或者执行完返回null(让spring去实例化)
				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
				// 如果其中一个有返回值,循环调用每个postProcessAfterInitialization方法,直到有一个返回值为null(没有实例化成功)。否则返回具体的值(自己实例化成功)。这里主要是为了Bean的AOP
				if (bean != null) {
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
				}
			}
		}
		// bean有值说明实例化成功,下次的这个判断不会进来,否则会继续执行
		mbd.beforeInstantiationResolved = (bean != null);
	}
	// 返回当前的处理过的Bean
	return bean;
}

spring本身的实例化方法

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

	// 实例化bean
	// Instantiate the bean.
	BeanWrapper instanceWrapper = null;
	// 这个Bean是单例的
	if (mbd.isSingleton()) {
		// 有可能在本Bean创建之前,就有其他Bean把当前Bean给创建出来了(比如依赖注入过程中)。factoryBean需要重新创建
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		// 创建Bean实例:推断构造方法,@Bean的处理
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	// 得到Bean对象
	Object bean = instanceWrapper.getWrappedInstance();
	// 得到Bean的类型
	Class<?> beanType = instanceWrapper.getWrappedClass();
	if (beanType != NullBean.class) {
		mbd.resolvedTargetType = beanType;
	}

	// 后置处理合并后的BeanDefinition(MergedBeanDefinitionPostProcessor):比如可以进行初始化方法的设置,比如添加属性值。spring友谊个默认的实现去寻找注入点。
	// Allow post-processors to modify the merged bean definition.
	synchronized (mbd.postProcessingLock) {
		if (!mbd.postProcessed) {
			try {
				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.
	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");
		}
		// 循环依赖-添加到三级缓存
		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
	}

	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
		// 属性填充
		populateBean(beanName, mbd, instanceWrapper);  //getBean()

		// 初始化:包括三个回调以及初始化前中后
		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) {
		// 从一级、二级缓存中获取Bean
		Object earlySingletonReference = getSingleton(beanName, false);
		// 获取到了
		if (earlySingletonReference != null) {
			// 是当前Bean,放入二级缓存
			if (exposedObject == bean) {
				exposedObject = earlySingletonReference;
			}
			else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
				// beanName被哪些bean依赖了,现在发现beanName所对应的bean对象发生了改变,那么则会报错
				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(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 " +
							"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
				}
			}
		}
	}

	// Register bean as disposable.
	// 处理Bean销毁前要执行的方法
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
	}

	return exposedObject;
}

属性填充:populateBean源码分析

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
	// Bean不存在的时候,直接返回或者抛异常
	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;
		}
	}

	// 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.
	// 实例化后,属性设置之前。循环调用每个实现postProcessAfterInstantiation的方法
	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
			if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
				return;
			}
		}
	}

	// 得到所有的属性值
	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

	// 依赖注入的逻辑
	int resolvedAutowireMode = mbd.getResolvedAutowireMode();
	// 这个判断是spring自带的依赖注入逻辑。可以在@Bean上配置autowire属性配置ByName或者ByType(已过期)
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		// MutablePropertyValues是PropertyValues具体的实现类
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// Add property values based on autowire by name if applicable.
		// ByName找的是set方法,比如setXxxxx就会找xxxx,setName就会找Name
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// Add property values based on autowire by type if applicable.
		// ByType找的是set方法,从Bean中找到当前类型的入参,进行传入
		if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			autowireByType(beanName, mbd, bw, newPvs);
		}
		pvs = newPvs;
	}

	// 获取是否有实现InstantiationAwareBeanPostProcessor的方法,这里主要使用postProcessProperties方法。
	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
	// 获取是否需要进行依赖注入
	boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

	PropertyDescriptor[] filteredPds = null;
	if (hasInstAwareBpps) {
		// 属性为空,获取需要注入的信息
		if (pvs == null) {
			pvs = mbd.getPropertyValues();
		}
		for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
			// 这里会调用AutowiredAnnotationBeanPostProcessor的postProcessProperties()方法,会直接给对象中的属性赋值。真正的处理@Autowired、@Resource、@Value注解
			// AutowiredAnnotationBeanPostProcessor内部并不会处理pvs。直接返回自己设置的PropertyValues对象(可以在实例化前设置)。
			PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
			// 这里的含义是程序员自己已经给属性赋值了,就不需要Spring给他赋值。这里是程序员没有赋值,所以需要Spring进行赋值
			if (pvsToUse == null) {
				// 第一次进来一般为空
				if (filteredPds == null) {
					filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
				}
				// 和postProcessProperties类似,但是已经过期了
				pvsToUse = bp.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);
	}

	// 如果当前Bean中的BeanDefinition中设置了PropertyValues,那么最终将是PropertyValues中的值,覆盖@Autowired
	if (pvs != null) {
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

初始化逻辑:initializeBean源码分析

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
	// 这里主要进行了三个Aware回调
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
			invokeAwareMethods(beanName, bean);
			return null;
		}, getAccessControlContext());
	}
	else {
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;

	// 初始化前:主要的实现有初始化方法@postconstruct,很多的Aware回调都在初始化前
	if (mbd == null || !mbd.isSynthetic()) {
		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);
	}

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

	return wrappedBean;
}

private void invokeAwareMethods(String beanName, Object bean) {
	// 实现了Aware以及其子类
	if (bean instanceof Aware) {
		// BeanNameAware回调
		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);
		}
	}
}

结束语

  • 获取更多本文的前置知识文章,以及新的有价值的文章,让我们一起成为架构师!
  • 关注公众号,可以让你对MySQL、并发编程、spring源码有深入的了解!
  • 关注公众号,后续持续高效的学习JVM!
  • 这个公众号,无广告!!!每日更新!!!
    作者公众号.jpg
posted @ 2022-02-22 23:43  程序java圈  阅读(136)  评论(0编辑  收藏  举报