既然是源码分析,那最好的办法还是编写一个测试用例,然后 debug 来看程序是怎样运行的。 测试例子:

public static void main(String[] args) {  
    ApplicationContext context=new AnnotationConfigApplicationContext(TestConfiguration.class);  
    TestBean tb= (TestBean) context.getBean("testBean");  
}
@Configuration  
public class TestConfiguration {  
    @Bean("testBean")  
    @Scope("prototype")  
    public TestBean testBean(){  
        return new TestBean();  
    }  
}

通过追踪 ApplicationContext 的 getBean() 方法,最后会进入到 AbstractBeanFactory 的 doGetBean() 方法里。

doGetBean方法

该方法会尝试去获取已经存在的bean,如果已经存在,则会返回该bean,否则将会进行bean的创建。

// AbstractBeanFactory#doGetBean

protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
	//去除工厂引用前缀,将别名转换成规范命名
	String beanName = this.transformedBeanName(name);
	//获取已经存在的bean,如果已经存在,则会直接返回
	Object sharedInstance = this.getSingleton(beanName);
	Object bean;
	if (sharedInstance != null && args == null) {
		if (this.logger.isTraceEnabled()) {
			if (this.isSingletonCurrentlyInCreation(beanName)) {
				this.logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
			} else {
				this.logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
			}
		}
		bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
	} else {
		if (this.isPrototypeCurrentlyInCreation(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}

		//处理父容器存在的情况
		BeanFactory parentBeanFactory = this.getParentBeanFactory();
		if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
			String nameToLookup = this.originalBeanName(name);
			if (parentBeanFactory instanceof AbstractBeanFactory) {
				return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
			}

			if (args != null) {
				return parentBeanFactory.getBean(nameToLookup, args);
			}

			if (requiredType != null) {
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}

			return parentBeanFactory.getBean(nameToLookup);
		}

		if (!typeCheckOnly) {
			this.markBeanAsCreated(beanName);
		}

		try {
			//合并父类的类定义
			RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
			this.checkMergedBeanDefinition(mbd, beanName, args);

			//保证当前bean所依赖的bean的初始化
			//获取bean所依赖的bean名
			String[] dependsOn = mbd.getDependsOn();
			if (dependsOn != null) {
				for (String dep : dependsOn) {
					if (isDependent(beanName, dep)) {
						//两个Bean循环依赖是不允许的,会直接抛出错误
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
								"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
					}
					registerDependentBean(dep, beanName);
					try {
						// 获取所依赖的bean
						getBean(dep);
					}
					catch (NoSuchBeanDefinitionException ex) {
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
								"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
					}
				}
			}
		   
			//创建单例bean
			if (mbd.isSingleton()) {
				sharedInstance = this.getSingleton(beanName, () -> {
					try {
						//创建bean,关键
						return this.createBean(beanName, mbd, args);
					catch (BeansException ex) {
						// Explicitly remove instance from singleton cache: It might have been put there
						// eagerly by the creation process, to allow for circular reference resolution.
						// Also remove any beans that received a temporary reference to the bean.
						destroySingleton(beanName);
						throw ex;
					}
				});
				bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
			//prototype类型的bean,每次都要创建
			} else if (mbd.isPrototype()) {
				var11 = null;

				Object prototypeInstance;
				try {
					this.beforePrototypeCreation(beanName);
					prototypeInstance = this.createBean(beanName, mbd, args);
				} finally {
					this.afterPrototypeCreation(beanName);
				}

				bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
			} else {
				String scopeName = mbd.getScope();
				if (!StringUtils.hasLength(scopeName)) {
					throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
				}
				Scope scope = this.scopes.get(scopeName);
				if (scope == null) {
					throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
				}
				try {
					Object scopedInstance = scope.get(beanName, () -> {
						beforePrototypeCreation(beanName);
						try {
							return createBean(beanName, mbd, args);
						}
						finally {
							afterPrototypeCreation(beanName);
						}
					});
					bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
				}
				catch (IllegalStateException ex) {
					throw new BeanCreationException(beanName,
							"Scope '" + scopeName + "' is not active for the current thread; consider " +
							"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
							ex);
				}
			}
		} catch (BeansException var26) {
			this.cleanupAfterBeanCreationFailure(beanName);
			throw var26;
		}
	}

	if (requiredType != null && !requiredType.isInstance(bean)) {
		try {
			T convertedBean = this.getTypeConverter().convertIfNecessary(bean, requiredType);
			if (convertedBean == null) {
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			} else {
				return convertedBean;
			}
		} catch (TypeMismatchException var25) {
			if (this.logger.isTraceEnabled()) {
				this.logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", var25);
			}

			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
		}
	} else {
		return bean;
	}
}

singletonprototype 对象在创建时的差别在:一个需要判断是否存在,存在则直接返回;另一个每次获取时都创建。

getSingleton(beanName, allowEarlyReference)方法

该方法会去Map缓存中获取已经存在的bean。

//DefaultSingletonBeanRegistry#getSingleton

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	//从map中获取bean,如果存在则直接返回
	Object singletonObject = this.singletonObjects.get(beanName);
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		synchronized (this.singletonObjects) {
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}

getSingleton(beanName, singletonFactory)方法

// DefaultSingletonBeanRegistry#getSingleton

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
	Assert.notNull(beanName, "Bean name must not be null");
	synchronized (this.singletonObjects) {
		Object singletonObject = this.singletonObjects.get(beanName);
		//判断bean是否存在
		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 + "'");
			}
			beforeSingletonCreation(beanName);
			boolean newSingleton = false;
			boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
			if (recordSuppressedExceptions) {
				this.suppressedExceptions = new LinkedHashSet<>();
			}
			try {
				//调用创建对象的方法,调用的是上面的createBean()方法
				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;
	}
}

createBean方法

//AbstractAutowireCapableBeanFactory#createBean

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 {
		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.
		//实例化前,给InstantiationAwareBeanPostProcessors一个机会代理对象
		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 [[AbstractBeanFactory的getBean方法#doCreateBean方法]]
		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);
	}
}

resolveBeforeInstantiation方法

该方法能用于在bean实例化之前执行自定义的 InstantiationAwareBeanPostProcessor 对象。

// AbstractAutowireCapableBeanFactory#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.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			Class<?> targetType = determineTargetType(beanName, mbd);
			if (targetType != null) {
				//调用InstantiationAwareBeanPostProcessors的postProcessBeforeInstantiation方法
				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
				if (bean != null) {
					//调用BeanPostProcessors的postProcessAfterInitialization方法
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
				}
			}
		}
		mbd.beforeInstantiationResolved = (bean != null);
	}
	return bean;
}

doCreateBean方法

主要的处理流程在这个方法里,这个方法主要做了对象的创建和对象的初始化。

// AbstractAutowireCapableBeanFactory#doCreateBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
        }

        if (instanceWrapper == null) {
			//创建对象实例,实例化
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }

        Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        synchronized(mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                } catch (Throwable var17) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
                }

                mbd.postProcessed = true;
            }
        }

		//先将实例化完成的对象放入到缓存中,用来解决循环引用的问题
        boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
        if (earlySingletonExposure) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
            }

            this.addSingletonFactory(beanName, () -> {
                return this.getEarlyBeanReference(beanName, mbd, bean);
            });
        }

        Object exposedObject = bean;

        try {
			//初始化对象(填充属性值)
            this.populateBean(beanName, mbd, instanceWrapper);
            exposedObject = this.initializeBean(beanName, exposedObject, mbd);
        } catch (Throwable var18) {
            if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
                throw (BeanCreationException)var18;
            }

            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = this.getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                    String[] dependentBeans = this.getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                    String[] var12 = dependentBeans;
                    int var13 = dependentBeans.length;

                    for(int var14 = 0; var14 < var13; ++var14) {
                        String dependentBean = var12[var14];
                        if (!this.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.");
                    }
                }
            }
        }

        try {
			//如果一个bean在定义时设置了destory方法或者实现了DisposableBean接口的,在此处注册,以便在销毁bean时进行回调
            this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
            return exposedObject;
        } catch (BeanDefinitionValidationException var16) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
        }
    }

createBeanInstance方法

创建对象实例,有两种方式创建对象,一个是通过无参构造方法,另一个是通过有参构造方法。

// AbstractAutowireCapableBeanFactory#createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
	// Make sure bean class is actually resolved at this point.
	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);
		}
	}

	// Candidate constructors for autowiring?
	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);
}

instantiateBean方法

无参构造方法实例化。

//AbstractAutowireCapableBeanFactory#instantiateBean

protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
	try {
		Object beanInstance;
		if (System.getSecurityManager() != null) {
			beanInstance = AccessController.doPrivileged(
					(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
					getAccessControlContext());
		}
		else {
			//实例化bean
			beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
		}
		BeanWrapper bw = new BeanWrapperImpl(beanInstance);
		initBeanWrapper(bw);
		return bw;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
	}
}
instantiate方法
//SimpleInstantiationStrategy#instantiate

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
	//如果没有方法重写
	if (!bd.hasMethodOverrides()) {
		Constructor constructorToUse;
		synchronized(bd.constructorArgumentLock) {
			constructorToUse = (Constructor)bd.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				Class<?> clazz = bd.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}

				try {
					if (System.getSecurityManager() != null) {
						clazz.getClass();
						constructorToUse = (Constructor)AccessController.doPrivileged(() -> {
							return clazz.getDeclaredConstructor();
						});
					} else {
						//通过反射获取构造方法
						constructorToUse = clazz.getDeclaredConstructor();
					}

					bd.resolvedConstructorOrFactoryMethod = constructorToUse;
				} catch (Throwable var9) {
					throw new BeanInstantiationException(clazz, "No default constructor found", var9);
				}
			}
		}
		//通过构造方法实例化一个类,并返回
		return BeanUtils.instantiateClass(constructorToUse, new Object[0]);
	} else {
		return this.instantiateWithMethodInjection(bd, beanName, owner);
	}
}

populateBean方法

填充对象实例,主要根据属性名和属性类型进行填充。例如: private Integer i , Integer 即是属性类型, i 为属性名。

//AbstractAutowireCapableBeanFactory#populateBean

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;
		}
	}
	
	// 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.
	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}
	}
	
	//获取bean的属性列表
	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
	
	int resolvedAutowireMode = mbd.getResolvedAutowireMode();
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// Add property values based on autowire by name if applicable.
		//通过属性名注入依赖
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// Add property values based on autowire by type if applicable.
		//通过属性类型注入依赖
		if (resolvedAutowireMode == 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) {
		//将属性应用于bean
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

autowireByName方法

//AbstractAutowireCapableBeanFactory#autowireByName

protected void autowireByName(
		String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

	//获取bean的非简单属性
	String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		if (containsBean(propertyName)) {
			//获取属性对应的bean实例
			Object bean = getBean(propertyName);
			//将获取到的bean加入到pvs
			pvs.add(propertyName, bean);
			registerDependentBean(propertyName, beanName);
			if (logger.isTraceEnabled()) {
				logger.trace("Added autowiring by name from bean name '" + beanName +
						"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
						"' by name: no matching bean found");
			}
		}
	}
}

Spring 认为的简单属性包括:基本类型、String 等,详细可以见 BeanUtils.isSimpleProperty() 方法。

autowireByType方法

//AbstractAutowireCapableBeanFactory#autowireByType

protected void autowireByType(
		String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

	TypeConverter converter = getCustomTypeConverter();
	if (converter == null) {
		converter = bw;
	}

	Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
	//获取bean的非简单属性
	String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
	for (String propertyName : propertyNames) {
		try {
			PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
			// Don't try autowiring by type for type Object: never makes sense,
			// even if it technically is a unsatisfied, non-simple property.
			//忽略Object对象
			if (Object.class != pd.getPropertyType()) {
				//获取属性对应的写方法(setter方法)的参数
				MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
				// Do not allow eager init for type matching in case of a prioritized post-processor.
				boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
				//依赖描述符
				DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
				//解析依赖
				Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
				if (autowiredArgument != null) {
					//将解析出来的bean加入到pvs中
					pvs.add(propertyName, autowiredArgument);
				}
				for (String autowiredBeanName : autowiredBeanNames) {
					registerDependentBean(autowiredBeanName, beanName);
					if (logger.isTraceEnabled()) {
						logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
								propertyName + "' to bean named '" + autowiredBeanName + "'");
					}
				}
				autowiredBeanNames.clear();
			}
		}
		catch (BeansException ex) {
			throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
		}
	}
}

InitializeBean

初始化Bean,包括应用工厂回调、init 方法和 BeanPostProcessors

//AbstractAutowireCapableBeanFactory#initializeBean

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 {
		//执行三类接口的回调BeanNameAware、BeanClassLoaderAware、BeanFactoryAware #TODO
		invokeAwareMethods(beanName, bean);
	}

	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		//调用 BeanPostProcessors 的postProcessBeforeInitialization方法,其中包括ApplicationContextAware接口的 #TODO
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		//如果bean实现了InitializingBean接口,则调用其afterPropertiesSet方法;
		//或者bean实现自定义了init方法,则会调用其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()) {
		//调用 BeanPostProcessors的postProcessAfterInitialization方法
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}

	return wrappedBean;
}

addSingletonFactory方法

将实例化完成但没初始化的单例的bean加入到map中。用于解决循环引用

// DefaultSingletonBeanRegistry#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)) {
			this.singletonFactories.put(beanName, singletonFactory);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
}

解决的问题

循环引用

循环引用是指A、B两个类相互引用。

@Component  
public class ClassA {  
    @Autowired  
	ClassB classB;  
}
@Component  
public class ClassB {  
    @Autowired  
	ClassA classA;  
}

当A实例化完成后,在进行属性装配时,会去获取B,如果B还没创建,则会去创建B。当在B实例化完成后,在进行属性装配时,会去获取A,但是此时A还没有创建完成,这就会造成循环引用。 Spring的解决办法为:在A实例化完成后,会放在缓存Map里面。等B去获取A时,会直接去缓存里面获取,而不会再创建。 实例化完成后放入缓存的代码在 [[bean的创建过程分析#addSingletonFactory方法|addSingletonFactory方法]],去先去缓存获取bean的代码在 [[bean的创建过程分析#getSingleton beanName allowEarlyReference 方法|getSingleton方法]] 方法里。其中Spring是使用了[[三级缓存]]来解决。

循环依赖

Spring处理两个bean循环依赖的方式是直接抛出错误,代码在 [[bean的创建过程分析#doGetBean方法|doGetBean方法]] ![[spring-循环依赖.png]]

总结

获取bean的时候,会首先从三级缓存里获取bean,如果已经存在则返回该bean。如果没有,则去创建bean。

// 从三级缓存中获取bean
Object sharedInstance = getSingleton(beanName);

创建bean的话,主要分为3个过程:实例化,属性注入,初始化。

  1. 实例化。分为有参构造方法实例化和无参构造方法实例化。无参构造方法最后通过反射获取构造方法进行实例化。 实例化完成后会把实例化完成但还没填充属性的对象放到三级缓存中,用来解决循环依赖。
  2. 属性注入。获取当前bean的属性,并获取属性对应的bean实例。
  3. 初始化。

三级缓存

缓存 名称 作用
一级 singletonObjects 存放初始化后的单例对象,也就是完成的bean对象
二级 earlySingletonObjects 存放实例化,未完成初始化的单例对象(未完成属性注入的对象),也是用来解决性能问题
三级 singletonFactories 存放ObjectFactory对象,存放的是工厂对象,主要用来解决循环依赖和aop的问题

参考

  1. BeanFactory getBean源码分析
  2. Spring IOC 容器源码分析 - 填充属性到 bean 原始对象 - SegmentFault 思否
  3. Spring源码分析之Bean的创建过程详解 - 雕爷的架构之路 - 博客园