一、前言
Spring的Bean的实例化过程源码分析太过复杂,为了避免篇章过长,这里分为上下篇来进行分析,大家可以先去阅读上篇Spring源码解析(5)之bean实例化过程(上)_jokeMqc的博客-CSDN博客,然后接着再来阅读这篇。
getBean的生命周期图:
1.1getSingleton获取单例
根据Scope获取单例,在这个方法中其实是使用了回调方法,使得程序可以在创建单例的前后做一些准备以及处理操作,而正在获取单例Bean是ObjectFactory的getObject()方法,该方法做的一些准备跟操作为:
- 检查该换是否已经加载过该bean。
- 若没有加载过,则将当前的bean标记为正在加载的状态。(这个标记则比较的重要,因为在第一次去缓存加载bean的时候,当在单例缓存池加载不到,则判断当前bean是否正在加载然后才去二级缓存里面去加载)
- 通过调用参数传入的ObjectFactory的getObject()方法来实例化bean。
- 加载单例bean后处理方法调用。
- 移除当前加载bean的缓存。
- 将结果记录到缓存并删除加载bean过程中所记录的各种辅助状态(如二级缓存、三级缓存)。
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
// 从缓存中获取bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 做标记,把正在创建的bean标记为true,singletonsCurrentlyInCreation
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
// 调用单实例bean的创建
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 加入到缓存中
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
1.1.1addSingleton添加缓存
将实例化好的bean加入到单例缓存池中,并从早期对象缓存和解决循环依赖缓存中移除。1
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 加入到缓存中
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
// 从早期对象缓存和解决循环依赖缓存中移除
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
1.2 createBean 创建bean
之前有提过Spring正在做事情的方法名一般是以doxxxx开头,可以看出我们正在创建bean的是doCreateBean,从代码中我们可以总结为一下几个步骤:
- 根据设置的class属性或者根据beanName来解析class
- 对overrider属性进行标记以及验证。
- 给bean的处理器一个机会有生成代理对象返回,后面会在aop模块详细讲。
- 创建bean
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 根据beanName和Bean定义解析class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 给bean的处理器一个机会有生成代理对象返回,后面会在aop模块详细讲
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);
}
// 真正进行主要的业务逻辑来创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
1.2.1 doCreateBean真正去创建bean
doCreateBean,这里我们来大概看下这个方法的主干流程,具体的方法分析我们会在下一节的循环依赖中会具体分析对应的源码。
- 如果是单例则首先需要清楚缓存。
- 实例化bean,将BeanDefinition转换为BeanWrapper。这个转换是一个非常复杂的过程,大致的过程可以如下, (1)如果存在工厂方法则使用工厂方法进行初始化。(2)一个类有多个构造函数,每个构造函数都有不同的参数,所以需要根据参数锁定构造函数并进行初始化。(3)如果既不存在工厂方法也不存在带有参数的构造函数,则使用默认的构造函数进行bean的实例化。
- 依赖处理,addSingletonFactory这个方法就比较关键了,spring会有循环依赖的情况,A中有B,B中有A,Spring中处理循环依赖的方式就是当创建B的时候,涉及到创建A的步骤时,并不是直接去再次创建A,而是通过放入缓存中的ObjectFactory来创建实例这样子就解决了循环依赖,其实大家看源码也可以知道,为什么构造函数的循环依赖,Spring无法解决,因为此时的早期对象还未暴露出去(放入缓存)。
- 属性填充。
- 调用bean的后置处理器以及InitializingBean和自己自定义的方法进行初始化
- 注册DisPosableBean,如果配置了destroy-method,这里就需要注册以便于在销毁时候调用
- 完成创建并返回。
// 真正创建bean的逻辑
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 调用构造方法来创建bean实例
if (instanceWrapper == null) {
/**
* 如果存在工厂方法则使用工厂方法来进行实例化
* 一个类有多个构造函数,每个构造函数的参数都不同,所以需要根据入参来锁定构造函数然后进行初始化
* 如果既不存在工厂方法又不存在带有参数的构造方法,则使用默认的构造函数进行初始化
**/
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
mbd.resolvedTargetType = beanType;
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
/**
* bean的后置处理器
* bean合并后的处理,
**/
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是否需要暴露到缓存对象中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 暴露早期对象到缓存中来解决循环依赖
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 为当前的bean填充属性,发现依赖等解决循环依赖就是在这个地方
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 调用bean的后置处理器以及InitializingBean和自己自定义的方法进行初始化
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) {
// 去缓存中获取对象,只有没有发生循环依赖的时候,earlySingletonReference才会为空
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
// 检查当前的bean在初始化方法中有没有被增强过(代理过)
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
// 注册DisposableBean。如果配置了destroy-method,这里注册需要以便在销毁时调用
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
1.2.2 addSingletonFactory 提早暴露对象解决循环依赖
这里会把早期对象先放入到缓存中,来解决循环依赖问题。
// 提前暴露对象
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
// 把bean作为ObjectFactory提前暴露出来
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
1.2.3 populateBean 属性填充
给创建好的bean进行属性赋值,虽然看这个方法虽然不是很长,但是调用的细节就比较复杂,不过我们看IOC源码需要抓主干,有些方法我们可以看做是一个黑盒方法,只要知道他是做什么的,不需要每一行去了解。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
// 从bean定义中获取属性列表
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
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.
/**
* 在属性填充之前,给InstantiationAwareBeanPostProcessors类型的后置处理器一个修改bean状态的机会
* 比如用户实现一个InstantiationAwareBeanPostProcessors类型的后置处理器,并通过postProcessAfterInstantiation方法
* 中向bean的成员
**/
boolean continueWithPropertyPopulation = true;
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;
}
}
}
}
//上面返回为flase 表示你已经通过自己写的InstantiationAwareBeanPostProcessor 类型的处理器已经设置过bean的属性值了,
if (!continueWithPropertyPopulation) {
return;
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs);
}
1.2.4initializeBean初始化bean
初始化bean。
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
// 调用bean实现的xxAware接口
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 调用bean的后置处理器的before接口
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用initianlBean方法和自定义的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()) {
// 调用bean的后置处理器的post方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}