Bean的创建
我们都知道spring对于单例的bean,会通过getBean方法来触发实例的生成
下面是Bean创建的流程图

getBean
// AbstractBeanFactory.java
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
doGetBean
这里主要关注下单例bean的创建过程
// AbstractBeanFactory.java
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 对bean的名称进行转换,这里做的有下面两件事
// 1. 去掉beanName前的&
// 2. 如果beanName是别名,对别名进行转化
String beanName = transformedBeanName(name);
Object beanInstance;
// Eagerly check singleton cache for manually registered singletons.
// <1> 获取单例对象
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
// <2> 如果成功获取单例对象,那么如果该对象如果是factoryBean,那么会进一步处理,返回处理后的对象
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// 合并当前BeanDefinition和其父BeanDefinition
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 优先创建当前bean依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
// 判断是否发生了循环依赖,如果发生了循环依赖直接报错
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 省略
// Create bean instance.
// <3>没有获取到单例对象,那么进行创建
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return 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;
}
});
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 省略
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
}
}
return adaptBeanInstance(name, beanInstance, requiredType);
}
getSingleton
首先看下如何通过<3>处的getSingleton方法来创建单例实例
// AbstractBeanFactory.java
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// <1>尝试从singletonObjects中来获取已经创建好的实例
Object singletonObject = this.singletonObjects.get(beanName);
// <2>判断目前没有已经创建好的实例
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 + "'");
}
// <3> 标记当前bean正在创建
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// <4> 通过工厂创建单例实例
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;
}
// <5> 将bean正在创建中的标记删除
afterSingletonCreation(beanName);
}
// <6> 将创建好的单例实例放到singleObjects中,此时bean已经创建完成
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
beforeSingletonCreation
这里主要执行的是创建单例实例之前的一些逻辑
这里主要的逻辑就是将指定的bean放入到singletonsCurrentlyInCreation集合中,标志当前的bean正在进行创建
// AbstractBeanFactory.java
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
singleFactory.getObject
这里主要是创建单例实例的逻辑
这里的singleFactory是一个function interface,主要逻辑在createBean方法中
// AbstractBeanFactory.java
sharedInstance = getSingleton(beanName, () -> {
try {
return 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;
}
});
下面详细看下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.
// <1> 解析实际的bean类型
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
// <2> 处理lookup method
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.
// <3> 使用BeanPostProcessor来处理bean,这里主要是探测当前是否有InstantiationAwareBeanPostProcessor
// 如果有的话,会使用InstantiationAwareBeanPostProcessor对这个bean进行处理
// InstantiationAwareBeanPostProcessor本身也是一个BeanPostProcessor,和一般的BeanPostProcessor不同的是,可以在bean实例化前后进行处理,而BeanPostProcessor则是在初始化的前后对bean进行处理
// 这里另外需要注意,如果InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation返回的结果不是null,那么接下来第<4>步创建bean的操作就会短路,不会执行
// 也就是说InstantiationAwareBeanPostProcessor会使bean的正常实例化过程短路
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 {
// <4>创建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);
}
}
resolveBeforeInstantiation
这里首先看下上面的第<3>步,在实例化bean前做了哪些操作
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.
// 这里会判断容器中是否有InstantiationAwareBeanPostProcessor类型的bean
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取bean的类型
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation对bean进行处理
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 调用InstantiationAwareBeanPostProcessor的postProcessAfterInitialization对bean进行处理
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
可以看到,主要就是使用InstantiationAwareBeanPostProcessor实例的postProcessBeforeInstantiation和postProcessAfterInitialization来对指定的bean进行操作
默认情况下,会有如下几个InstantiationAwareBeanPostProcessor实例

doCreateBean
接下来看下正常情况下真正用来创建bean实例的地方doCreateBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// <1> 使用适当的方式来创建一个bean实例,此时会得到一个只是实例化之后的对象,没有进行属性注入
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// <2> 使用MergedBeanDefinitionPostProcessor来处理bean
synchronized (mbd.postProcessingLock) {
// 判断当前的bean definition是否经过MergedBeanDefinitionPostProcessor的处理
// 通过RootBeanDefinition上的postProcessed标志控制只会处理一次
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.
// <3> 判断当前处理的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是单例的并且正在创建,那么会将beanName -> 通过() -> getEarlyBeanReference实现的ObjectFactory映射添加到singletonFactories中
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// <4> 根据beanDefinition,设置bean实例的属性
// 如果aService依赖了bService,此时会通过getBean来创建bService的实例
populateBean(beanName, mbd, instanceWrapper);
// <5> 对bean进行初始化,调用工厂回调,init方法或者是bean post processor
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) {
// <6> 获取单例实例
// 如果singletonObjects中存在,那么直接返回
// 如果earlySingletonObjects中存在,那么直接返回
// 如果singletonFactories中存在,那么会从singletonFactories中取出对应的factory,然后返回factory.getObject的结果
// 并且将该factory从singletonFactories中移除,并且将生成的结果放到earlySingletonObjects中
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(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.
try {
// <7>
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
createBeanInstance
这里会根据BeanDefinition的信息,执行不同的策略来创建bean实例,主要有如下三种策略:
- 工厂方法
- 构造方法注入
- 简单的实例化
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);
// 如果bean的类型不是public的,直接报错
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());
}
// <1> 判断是否设置了instanceSupplier,如果设置了,会直接使用instanceSupplier来获取实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// <2> 判断是否设置了factoryMethod,如果设置了会尝试调用factoryBeanName或者当前bean对应factoryMethod的方法来创建获取实例
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// <3> 需要通过指定的构造方法并且将其他bean作为参数进行构造
// Shortcut when re-creating the same bean...
// 当重新创建bean的时候,会使用之前的解析结果,及resolvedConstructorOrFactoryMethod来判断是否解析出了需要使用的构造方法或者工厂方法
// constructorArgumentResolved来判断需要使用的构造方法的参数是否解析好了
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 判断是否解析出了需要使用的构造方法或者是工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
// 判断方法是否需要使用其他bean作为方法的入参
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//需要使用的构造方法已经解析好了
if (resolved) {
if (autowireNecessary) {
// 构造方法注入创建bean实例
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认构造方法
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// <4> 通过SmartInstantiationAwareBeanPostProcessor来决定候选的构造方法
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?
// <5> 使用preferredConstructor来进行实例化
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor
// <6> 默认情况,使用默认构造方法来创建
return instantiateBean(beanName, mbd);
}
applyMergedBeanDefinitionPostProcessors
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
方法比较简单,遍历当前容器中的MergedBeanDefinitionPostProcessor对BeanDefinition进行处理
默认情况会有如下3个PostProcessor

其中最重要的就是AutowiredAnnotationBeanPostProcessor,主要用来对@Autowired注解进行处理
addSingletonFactory
当判断当前处理的bean是单例并且允许循环引用的存在,并且当前bean正在创建,那么会将ObjectFactory添加到singletonFactories中
主要是用来解决bean之间的循环依赖
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);
}
}
}
populateBean
这里主要做的就是对bean中属性的设置
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.
// <1> 使用InstantiationAwareBeanPostProcessor对生成的bean实例进行后置处理
// 这里主要是在spring自带的自动注入操作之前,执行用户自定义的注入
// postProcessAfterInstantiation的返回代表是否需要继续后续spring自带的自动注入
// 也就是说这里的操作可以使spring的注入操作短路
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
// 这里会获取到使用<property>标签设置的属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// <2> 这里会遍历当前bean中的所有属性,如果属性不是简单类型,具有setter方法并且propertyValues中没有对应该属性的值,那么会根据配置的注入模式来将属性的值放入propertyValues中
// 默认情况下 resolvedAutowireMode是AUTOWIRE_NO不会走下面的注入逻辑
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;
}
// <3> 处理propertiesValue,比如在applicationContext.xml文件中通过<property>标签设置的bean的属性值
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// 调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues来处理PropertyValues
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
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);
}
// 将上面经过处理的propertyValues设置到bean中
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
initializeBean
这里主要做的回调各种Aware接口的方法
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
// <1> 回调BeanNameAware,BeanClassLoaderAware,BeanFactoryAware的回调方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
// <2> 回调BeanPostProcessor的postProcessBeforeInitialization方法对bean实例进行处理
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// <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>回调回调BeanPostProcessor的postProcessAfterInitialization方法对bean实例进行处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
getSingleton
这个方法的主要作用就是为了获取单例实例
会从下面三个map中来尝试获取实例:
- singletonObjects
- earlySingletonObjects
- singletonFactory
之所以使用三个map,是为了解决spring中的循环依赖问题
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
afterSingletonCreation
afterSingletonCreation会在bean实例完全创建完成之后调用,主要的作用就是将当前bean从singletonCurrentlyInCreation中移除,从而标志当前bean已经生成
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
addSingleton
addSingleton的作用就是将当前已经创建好的bean实例放到singletonObjects中,并且从singletonFactories和earlySingletonObjects中移除,并添加到registerSingletons中,标志当前bean已经创建
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
Spring Bean 创建流程
本文深入解析Spring框架中Bean的创建过程,包括Bean的实例化、属性填充、初始化等关键步骤,以及解决循环依赖的机制。
4220

被折叠的 条评论
为什么被折叠?



