背景
在Spring中,Bean的加载和管理是其核心功能之一,包括配置元数据解析、Bean定义注册、实例化、属性填充、初始化、后置处理器处理、完成创建和销毁等步骤。
源码入口
AbstractBeanFactory#doGetBean
具体源码流程如下:
bean加载流程(#getBean方法)分析:
1、提取beanName
-
提取FactoryBean修饰符,比如name=“&aa”,那么就要去掉&,使得name=“aa”
-
或者,提取指定的beanName,比如别名A->B的bean则返回B
2、从缓存中加载单例
创建单例时,为避免循环依赖,不等完全bean创建,就将创建bean的ObjectFactory提早曝光;即,ObjectFactory放到缓存Map中,一旦下一个bean需要依赖上个bean,就直接使用 ObjectFactory即可。
-
singletonObjects:key=BeanName,value=构造完成的bean实例
-
earlySingletonObjects:key=BeanName,value=构造完成的bean实例,用来解决循环依赖问题
-
singletonFactories:key=BeanName,value=ObjectFactory工厂实例
三级缓存实现原理
当Spring容器创建Bean时,首先会从singletonObjects缓存中查找Bean实例,如果能找到则直接返回。
-
如果在singletonObjects缓存中没有找到Bean实例,则从earlySingletonObjects缓存中查找,如果找到了一个未完成初始化的Bean实例,则将其返回,并在后续的处理中完成初始化。
-
如果在earlySingletonObjects缓存中也没有找到Bean实例,则从singletonFactories缓存中查找是否存在创建Bean实例的工厂对象,如果存在,则通过工厂对象创建一个新的Bean实例,并将工厂对象从singletonFactories缓存中移除。
-
如果在singletonFactories缓存中也没有找到工厂对象,则需要创建一个新的工厂对象,并放到singletonFactories缓存中,以便后续使用。
-
创建Bean实例时,如果Bean存在循环依赖,那么Spring框架会先创建一个用于创建Bean实例的工厂对象,放到singletonFactories缓存中。然后通过工厂对象创建一个新的Bean实例,并将其放到earlySingletonObjects缓存中,以便后续处理。
下面是DefaultSingletonBeanRegistry源码
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 【1】
if (singletonObject == null
&& isSingletonCurrentlyInCreation(beanName)) {
// 【2】
synchronized (this.singletonObjects) {
// 【3】
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 【4】
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 【5】
singletonObject = singletonFactory.getObject();
// 【6】
this.earlySingletonObjects.put(beanName, singletonObject);
// 【7】
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
代码分析:
-
【1】isSingletonCurrentlyInCreation 判断是否循环依赖
-
【2】用synchronized 锁住singleObjects一级缓存全局变量,确保线程安全,因为有3个全局变量要修改的
-
【3】从 earlySingletonObjects 二级缓存取 object
-
如果object不为空,说明bean正在被创建,则跳出来
-
如果object为空,说明bean没在被创建,需要执行下面逻辑
-
-
【4】从 singletonFactories 三级缓存取 ObjectFactory(某些方法提前初始化了ObjectFactory策略到 singletonFactories 中)
-
【5】如果object不为空,说明已经有预设好的ObjectFactory,可以实例化它:通过预设的getBean ObjectFactory@getObject() 创建bean实例
-
【6】记录到 earlySingletonObjects 中,说明此bean正在被创建
-
【7】earlySingletonObjects 和 singletonFactories是互斥的,因此要remove调
-
3、多例对象-是否创建中检测
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
单例才检测循环依赖,多例抛异常。
4、检测parentBeanFactory
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
缓存没有数据,直接转到父类工厂上去加载工厂方法
5、解析Defination类的类型转换,换成可用的BeanDefination
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
6、寻找递归解决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);
}
}
}
7、正式根据scope去创建bean
bean创建的特别之处
Spring 解决循环依赖依靠的是 Bean 的 " 中间态 " 这个概念,而这个中间态指的是已经实例化但还没初始化的状态 —>半成品。
实例化的过程又是通过构造器创建的,如果 A 还没创建好出来怎么可能提前曝光,所以构造器的循环依赖无法解决。
由于 spring 中的 bean 的创建过程为先实例化 再初始化 ( 在进行对象实例化的过程中不必赋值 ) 将实例化好的对象暴露出去, 供其他对象调用 , 然而使用构造器注入 , 必须要使用构造器完成对象的初始化的操作 ,就会陷入死循环的状态。
单例scope:实例化bean
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;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
代码分析:
-
实例化bean:createBean -》
-
doCreateBean -》,参考下面的源码分析【1】
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
-
createBeanInstance,参考下面的源码分析【2】
-
-
getSingleton:beanName是一个参数,另一个匿名函数则是ObjectFactory<?> singletonFactory,即构造bean的工厂方法
-
singletonObjects:添加经过了实例化+初始化的bean实例
-
singletonFactories:移除
-
earlySingletonObjects:移除
-
addSingleton(beanName, singletonObject):三级缓存的清理赋值
-
【1】源码addSingletonFactory:创建bean实例
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, 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);
}
}
}
代码分析:该方法用于添加单例工厂,主要功能包括:
-
检查传入的单例工厂是否为null,若为null则抛出异常。
-
同步锁住singletonObjects确保线程安全。
-
若singletonObjects中没有beanName对应的对象,则将singletonFactory放入singletonFactories映射中,并移除earlySingletonObjects中的对应项,最后将beanName加入registeredSingletons集合。
这也侧面说明了,bean还没有完全初始化,就把工厂方法提前暴露到了singletonFactories
【2】源码createBeanInstance: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);
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);
}
代码分析:
createBeanInstance 用于创建 Bean 的实例,负责根据不同的条件和配置来实例化 Bean,并处理相关的异常情况:
-
解析并验证 Bean 类。
-
如果允许,尝试从 Supplier 获取实例。
-
若配置了工厂方法,则通过工厂方法实例化。
-
否则,根据参数情况选择构造器自动装配或直接实例化。
初始化bean:填充属性
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean#populateBean
@SuppressWarnings("deprecation") // for postProcessPropertyValues
protected void populateBean(
String beanName, RootBeanDefinition mbd,
@Nullable BeanWrapper bw) {
//【1】
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
return;
}
}
//【2】
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//【3】
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();
}
//【4】
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);
}
//【5】
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
//【6】
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
代码分析:
-
【1】检查BeanWrapper是否为空,若为空且存在属性值,则抛出异常;否则跳过属性填充。
-
【2】若存在实例化需要的后置处理器,则调用它们对bean进行处理。
-
【3】根据自动装配模式(按名或按类型)添加属性值。
-
【4】调用实例化后置处理器处理属性值。
-
【5】检查依赖关系并进行依赖检查。
-
【6】应用最终的属性值到bean上
多例scope:实例化bean
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
代码分析:
-
createBean:流程参考单例scope的创建,是类似的。
8、通用:初始化bean & 注入依赖
之前已经实例化过bean了,现在则是完成注入属性;属性注入的顺序是,优先通过autowireByName,然后才是autowireByType。
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;
}
9、再执行当前bean的initializeBean初始化
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 {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
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);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
该Java函数initializeBean用于初始化一个Bean:
-
初始化前
-
根据系统安全设置,以特权操作方式或直接调用invokeAwareMethods方法,即Aware接口方法调用
-
执行BeanPostProcessor接口的postProcessBeforeInitialization方法,即Bean应用前置处理器
-
-
初始化时
-
调用InitializingBean接口的afterPropertiesSet方法,完成初始化
-
BeanPostProcessor接口的applyBeanPostProcessorsBeforeInitialization
-
调用初始化方法,对bean 进行初始化,若失败则抛出异常。
-
执行BeanPostProcessor接口的postProcessAfterInitialization方法,即对Bean应用后置处理器。
初始化后
-
DisposableBean接口的destroy方法执行(有必要的话)