创建bean的主要类
DefaultSingletonBeanRegistry
共享bean实例(单例bean实例)的通用注册表,实现了SingletonBeanRegistry. 允许注册表中注册的单例应该被所有调用者共享,通过bean名称获得。
三级缓存
在该类中,有如下三个属性,是bean的三级缓存
/** 一级缓存,保存singletonBean实例的映射: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
/** 二级缓存,保存早期未完全创建的Singleton实例的映射: bean name --> bean instance */
private final Map<String, Object> earlySingletonObjects = new HashMap(16);
/** 三级缓存,保存singletonBean生产工厂: bean name --> ObjectFactory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);
思考的两个问题:
- 为什么需要使用三级缓存?正常情况下二级缓存也可以解决循环依赖
- 第三级缓存中为什么存的是ObjectFactory,而不是Object?
如果第三级缓存中存的也是Object,那么就跟第二级缓存是一样了,没有意义了,那么第三级存在的必要性肯定跟这个缓存中存的是ObjectFactory有关系,那么重点就在ObjectFactory的getObject()方法
getSingleton(String beanName)
//获取beanName对应的bean,并且允许提前引用
public Object getSingleton(String beanName) {
return this.getSingleton(beanName, true);
}
getSingleton(String beanName, boolean allowEarlyReference)
- 如果allowEarlyReference为true,则可以从第三级缓存中获取该单例bean
- 如果allowEarlyReference为false,则不可从第三级缓存中获取该对象,即该单例bean不可提前引用
//获取单例bean,分别从一级缓存、二级缓存、(三级缓存中)中获取单例bean
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//先从一级缓存singletonObjects中获取单例bean对象
Object singletonObject = this.singletonObjects.get(beanName);
//如果从singletonObjects获取不到该对象 && 该对象正在创建中
if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
synchronized(this.singletonObjects) {
//从二级缓存earlySingletonObjects(提前引用的单例bean集合)中获取该对象
singletonObject = this.earlySingletonObjects.get(beanName);
//如果从二级缓存earlySingletonObjects没有获取到对象 && 允许提前引用
if (singletonObject == null && allowEarlyReference) {
//从正在创建的bean集合singletonFactories中获取该对象
ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//如果从singletonFactories中获取该对象不为空,则将其放入提前引用的单例集合中,并且从正在创建的集合singletonFactories中删除
singletonObject = singletonFactory.getObject();
//将其放入提前引用的单例集合中
this.earlySingletonObjects.put(beanName, singletonObject);
//从正在创建的集合singletonFactories中删除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
getSingleton(String beanName, ObjectFactory<?> singletonFactory)
//带有ObjectFactory参数的getSingleton方法
//给ObjectFactory.getObject()方法注入的逻辑是调用createBean()方法,见AbstractBeanFactory.doGetBean()中对该方法的调用
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized(this.singletonObjects) {
//从一级缓存中获取改bean
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!)");
}
this.beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = this.suppressedExceptions == null;
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet();
}
try {
//ObjectFactory是函数式接口
//getObejct()里的逻辑是调用createBean()并返回创建的bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
} catch (IllegalStateException var16) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw var16;
}
} catch (BeanCreationException var17) {
BeanCreationException ex = var17;
if (recordSuppressedExceptions) {
Iterator var8 = this.suppressedExceptions.iterator();
while(var8.hasNext()) {
Exception suppressedException = (Exception)var8.next();
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
this.afterSingletonCreation(beanName);
}
//如果是新增的单例,则添加到单例一级缓存中
if (newSingleton) {
this.addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
addSingleton(String beanName, Object singletonObject)
bean初始化完毕,放到singletonObjects(一级缓存)中,将bean对应的earlySingletonObjects(二级缓存)或者singletonFactories(三级缓存)清除
//将beanName所对应的bean放入到singletonObjects一级缓存中
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);
}
}
addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory)
//将beanName所对应的bean工厂放入到singletonFactories三级缓存中,其是解决循环依赖的关键
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);
}
}
}
beforeSingletonCreation
将当前正要创建的bean记录在正在创建的bean的缓存中。
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
AbstractBeanFactory
getBean
public Object getBean(String name) throws BeansException {
return this.doGetBean(name, (Class)null, (Object[])null, false);
}
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return this.doGetBean(name, requiredType, (Object[])null, false);
}
public Object getBean(String name, Object... args) throws BeansException {
return this.doGetBean(name, (Class)null, args, false);
}
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args) throws BeansException {
return this.doGetBean(name, requiredType, args, false);
}
doGetBean
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
String beanName = this.transformedBeanName(name);
//调用父类DefaultSingletonBeanRegistry中的getSingleton方法
Object sharedInstance = this.getSingleton(beanName);
Object bean;
//如果sharedInstance不为null,表示该bean 1.已经创建且初始化成功,或者2.正在创建中
if (sharedInstance != null && args == null) {
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
} else {
//如果sharedInstance为null
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 {
//获取合并后的bean的定义
RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
//check合并后的bean定义
this.checkMergedBeanDefinition(mbd, beanName, args);
//获取通过@dependsOn进行设置的依赖,该依赖不同于通过属性引用的依赖
String[] dependsOn = mbd.getDependsOn();
String[] var11;
//检查依赖关系,如果存在循环依赖,则直接抛异常
if (dependsOn != null) {
var11 = dependsOn;
int var12 = dependsOn.length;
for(int var13 = 0; var13 < var12; ++var13) {
//依赖的bean名称dep
String dep = var11[var13];
//检测bean是否存在循环依赖情况,如果存在循环依赖,直接抛异常
if (this.isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册bean的依赖关系
this.registerDependentBean(dep, beanName);
//获取依赖的bean
try {
this.getBean(dep);
} catch (NoSuchBeanDefinitionException var24) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", var24);
}
}
}
//判断bean的scope是单例、原生
if (mbd.isSingleton()) {
//如果该bean是单例,则调用getSingleton方法获取该单例bean
sharedInstance = this.getSingleton(beanName, () -> {
//这里的ObjectFactory使用的是函数编程,getObject()调用下面这个createBean方法
try {
return this.createBean(beanName, mbd, args);
} catch (BeansException var5) {
this.destroySingleton(beanName);
throw var5;
}
});
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
//如果该bean是原生的
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 = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
this.beforePrototypeCreation(beanName);
Object var4;
try {
var4 = this.createBean(beanName, mbd, args);
} finally {
this.afterPrototypeCreation(beanName);
}
return var4;
});
bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException var23) {
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", var23);
}
}
} 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) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
} else {
return bean;
}
}
DefaultSingletonBeanRegistry#getSingleton(beanName)
DefaultSingletonBeanRegistry#getSingleton(beanName,ObjectFactory)
ObjectFactory是函数时接口,在调用这个方法时,给ObjectFactory.getObject()注入的逻辑是调用AbstractAutowireCapableBeanFactory#createBean
AbstractAutowireCapableBeanFactory
createBean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
//1.解析beanName对应的Bean的类型,
Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 2.验证及准备覆盖的方法(对override属性进行标记及验证)
try {
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException var9) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var9);
}
Object beanInstance;
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 3.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例,达到“短路”效果
beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
// 3.1.如果bean不为空,则会跳过Spring默认的实例化过程,直接使用返回的bean
if (beanInstance != null) {
return beanInstance;
}
} catch (Throwable var10) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var10);
}
// 4.创建Bean实例(真正创建Bean的方法)
try {
beanInstance = this.doCreateBean(beanName, mbdToUse, args);
//返回创建的bean
return beanInstance;
} catch (ImplicitlyAppearedSingletonException | BeanCreationException var7) {
throw var7;
} catch (Throwable var8) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", var8);
}
}
resolveBeforeInstantiation
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// mbd不是合成的 && BeanFactory中存在InstantiationAwareBeanPostProcessor实现类
if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
// 解析beanName对应的Bean实例的类型
Class<?> targetType = this.determineTargetType(beanName, mbd);
if (targetType != null) {
// 实例化前的后置处理器应用,回调InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation方法
bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 回调BeanPostProcessor实现类的postProcessAfterInitialization方法
bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
//如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析
mbd.beforeInstantiationResolved = bean != null;
}
return bean;
}
applyBeanPostProcessorsBeforeInstantiation
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//AbstractAutoProxyCreator实现了该接口
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
doCreateBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
//实例化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}
//
if (instanceWrapper == null) {
// 根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper
//有三种方式创建Bean实例
//(1).instanceSupplier:如果该BeanDefinition中的instanceSupplier属性不为空,则使用这种方式创建bean
//(2).beanFactory:如果该BeanDefinition中的BeanFactory属性不为空,则使用这种方式创建bean
//(3).通过bean的构造函数,使用反射技术,自定义构造bean
instanceWrapper = this.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
// 允许post-processors修改合并后的bean定义
// 这些pos-processors是MergedBeanDefinitionPostProcessor的实现类
// MergedBeanDefinitionPostProcessor接口继承了BeanPostProcessor接口
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);
}
//设置postProcessed为true,表明该bean定义被post-processors执行过
mbd.postProcessed = true;
}
}
// 判断是否需要提早引用实例:单例 && 允许循环依赖 && 当前bean正在创建中
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
// 提前引用beanName的ObjectFactory,将其放入三级缓存singletonFactories中
// ObjectFactory是一个函数时接口,方法名是getObject()
// 请注意:1.这级缓存中存放的时ObjectFacotry
//2.通过getEarlyBeanReference获取bean,是一个比较复杂的过程,因此出现了二级缓存earlySingletonObjects
this.addSingletonFactory(beanName, () -> {
//当调用ObjectFactory.getObject()时会执行该方法体
return this.getEarlyBeanReference(beanName, mbd, bean);
});
}
//初始化bean实例
Object exposedObject = bean;
try {
//对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例
this.populateBean(beanName, mbd, instanceWrapper);
//对bean进行初始化
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);
}
//如果是提前引用的bean,则进行相关的验证
if (earlySingletonExposure) {
//进行循环依赖检查
Object earlySingletonReference = this.getSingleton(beanName, false);
//earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
if (exposedObject == bean) {
//如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
//如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例
// && 当前bean有被其他bean依赖
//拿到依赖当前bean的所有bean的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];
//尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
//移除失败的添加到 actualDependentBeans
actualDependentBeans.add(dependentBean);
}
}
//如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据”
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.");
}
}
}
}
// 注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
try {
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
} catch (BeanDefinitionValidationException var16) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
}
}
createBeanInstance实例化
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
Class<?> beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
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());
} else {
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return this.obtainFromSupplier(instanceSupplier, beanName);
} else if (mbd.getFactoryMethodName() != null) {
return this.instantiateUsingFactoryMethod(beanName, mbd, args);
} else {
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized(mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);
} else {
Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)) {
ctors = mbd.getPreferredConstructors();
return ctors != null ? this.autowireConstructor(beanName, mbd, ctors, (Object[])null) : this.instantiateBean(beanName, mbd);
} else {
return this.autowireConstructor(beanName, mbd, ctors, args);
}
}
}
}
}
applyMergedBeanDefinitionPostProcessors
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
Iterator var4 = this.getBeanPostProcessors().iterator();
while(var4.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var4.next();
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor)bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
DefaultSingletonBeanRegistry#addSingletonFactory
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;
}
}
//如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历执行InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法
//这里给任何InstantiationAwareBeanPostProcessor实现类一个机会,在bean的属性properties设置之前,修改bean的状态
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();
}
//如果实现了InstantiationAwareBeanPostProcessor接口,则执行postProcessProperties,postProcessPropertyValues方法
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;
}
}
}
//依赖检查,对应depends-on属性
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
// 将所有PropertyValues中的属性填充到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
AbstractAutoProxyCreator#postProcessAfterInstantiation
autowireByName
如果 autowire 设置为“byName”,则使用此方法填充指向其他bean的引用的属性值
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
}
}
}
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);
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.
if (Object.class != pd.getPropertyType()) {
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) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
CommonAnnotationBeanPostProcessor/AutowiredAnnotationBeanPostProcessor#postProcessProperties
CommonAnnotationBeanPostProcessor/AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
initializeBean初始化
初始化给定的 bean 实例,应用工厂回调方法、initMethod和 bean 初始化后的post-processor。
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
this.invokeAwareMethods(beanName, bean);
return null;
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
//调用初始化前post-processor
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}
//调用初始化方法方法init-method
try {
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
//调用初始化后post-processor
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
invokeAwareMethods
根据bean实现的Aware接口,调用相关的方法
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//如果bean实现了BeanFactoryAware接口,则将BeanFactory设置给该bean
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
applyBeanPostProcessorsBeforeInitialization
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
applyBeanPostProcessorsAfterInitialization
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
getEarlyBeanReference
//获取提前暴露的bean的引用
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
Iterator var5 = this.getBeanPostProcessors().iterator();
while(var5.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var5.next();
//AbstractAutoProxyCreator实现了该接口
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor)bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
其他相关接口与实现类
BeanFactoryAware
让实现该接口的Bean获取到BeanFactory的引用
public interface BeanFactoryAware extends Aware {
/**
*将BeanFactory提供给 bean 实例的回调。
*在填充普通bean属性之后(即populateBean()方法之后)
*但在初始化回调(例如 {@link InitializingBean#afterPropertiesSet()} 或自定义初始化方法)之前调用。
*
*/
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
BeanPostProcessor
postProcessBeforeInitialization
/**
* 在任何bean初始化回调方法调用之前(如 InitializingBean 的 {@code afterPropertiesSet} 或自定义初始化方法),会执行该方法。
* 此时bean已经被填充了属性值,即执行过了populateBean方法。
* 返回的 bean 实例可能是原始实例的经过包装后的bean。
* 默认实现是按原样返回给定的 {@code bean}
*
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
postProcessAfterInitialization
/**
* 在任何bean初始化回调方法调用之后(如 InitializingBean 的 {@code afterPropertiesSet} 或自定义初始化方法),会执行该方法。
* 此时bean已经被填充了属性值,即执行过了populateBean方法。
* 返回的 bean 实例可能是原始实例的经过包装后的bean。
* 默认实现是按原样返回给定的 {@code bean}
*
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
InstantiationAwareBeanPostProcessor
BeanPostProcessor的子接口,它添加了实例化前回调,以及实例化后但在设置显式属性或自动装配之前的回调。
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
}
postProcessBeforeInstantiation
//在目标 bean 被实例化之前回调该方法
//返回的 bean 对象可能是一个代理来代替目标 bean,有效地抑制目标 bean 的默认实例化。
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
postProcessAfterInstantiation
//在bean被实例化(通过构造函数或工厂方法)之后,但在Spring属性填充(来自显式属性或自动装配)发生之前,回调该方法
//这是在 Spring 的自动装配开始之前对给定 bean 实例执行自定义字段注入的理想回调。
//返回true,表示应该在bean上设置属性,该接口的正常实现类应该返回true
//返回false,表示应该跳过属性填充。
//返回false还将阻止在此bean实例上调用任何后续InstantiationAwareBeanPostProcessor 实例。
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
postProcessProperties
/**
* Post-process the given property values before the factory applies them to the given bean, without any need for property descriptors.
* 在工厂将给定的属性值应用于给定的bean之前对给定的属性值进行后置处理,无需任何属性描述符。
*
* @param pvs the property values that the factory is about to apply (never {@code null})
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean
*/
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return null;
}
postProcessPropertyValues
/**
*Post-process the given property values before the factory applies them to the given bean.
*Allows for checking whether all dependencies have been satisfied, for example based on a "Required" annotation on bean property setters.
*Also allows for replacing the property values to apply, typically through creating a new MutablePropertyValues instance based on the original PropertyValues, adding or removing specific values.
*在工厂将给定的属性值值应用于给定的bean之前对给定的属性值进行后置处理
*允许检查是否所有依赖项都已满足,例如基于 bean 属性设置器上的“必需”注释。
*还允许替换要应用的属性值,通常通过基于原始属性值创建新的 MutablePropertyValues 实例,添加或删除特定值。
*
*/
@Deprecated
@Nullable
default PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
SmartInstantiationAwareBeanPostProcessor
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {}
predictBeanType
//预测最终从该处理器的 {@link #postProcessBeforeInstantiation} 回调返回的 bean 的类型
@Nullable
default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
determineCandidateConstructors
//确定用于给定 bean 的候选构造函数
@Nullable
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
throws BeansException {
return null;
}
getEarlyBeanReference
//获取对指定 bean 的早期访问的引用,通常用于解析循环引用。
//回调方法使post-processors有机会尽早暴露包装器 - 即在目标 bean 实例完全初始化之前。
//暴露的对象应该等同于 {@link #postProcessBeforeInitialization} / {@link #postProcessAfterInitialization} 否则会暴露的对象。
//请注意,此方法返回的对象将用作 bean 引用,除非post-processor从所述后处理回调返回不同的包装器。
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
CommonAnnotationBeanPostProcessor
postProcessProperties
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
}
return pvs;
}
postProcessPropertyValues
@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
return postProcessProperties(pvs, bean, beanName);
}
AutowiredAnnotationBeanPostProcessor
postProcessProperties
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
postProcessPropertyValues
@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
return postProcessProperties(pvs, bean, beanName);
}
AbstractAutoProxyCreator
SmartInstantiationAwareBeanPostProcessor
接口继承自InstantiationAwareBeanPostProcessor
接口。
因此AbstractAutoProxyCreator
一般是通过InstantiationAwareBeanPostProcessor
接口的postProcessBeforeInstantiation方法和postProcessBeforeInstantiation方法来返回代理对象;
- postProcessBeforeInstantiation阶段:前置处理器一般返回null,除非有TargetSource,就是对象已经创建了,则直接返回改bean
- postProcessAfterInitialization阶段:如果在postProcessBeforeInstantiation阶段返回null,则待对象创建并初始化完成,再通过postProcessAfterInitialization方法使用动态代理根据实例对象创建增强的动态代理对象。
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
}
postProcessBeforeInstantiation
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
Object cacheKey = getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
// 如果我们有一个自定义的TargetSource,则在这里创建代理
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
// 创建动态代理对象
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
}
postProcessAfterInstantiation
public boolean postProcessAfterInstantiation(Object bean, String beanName) {
return true;
}
getEarlyBeanReference
//获取提前暴露出来的bean的引用
public Object getEarlyBeanReference(Object bean, String beanName) {
//生成该bean对应的cacheKey
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
//将该bean放入到earlyProxyReferences中用于表示该Bean执行过AOP
this.earlyProxyReferences.put(cacheKey, bean);
//如果需要的话,对给定的bean进行封装,例如,该bean需要被代理
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
postProcessAfterInitialization
//Create a proxy with the configured interceptors if the bean is identified as one to proxy by the subclass.
//如果 bean 被子类标识为代理,则使用配置的拦截器创建一个代理。
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
//如果该bean未执行过AOP,则进行封装,如果执行过,则不再进行封装
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
wrapIfNecessary
/**
* 如果需要的话,对给定的bean进行封装,例如,该bean需要被代理
* @param bean 原来的bean实例(the raw bean instance)
* @param beanName the name of the bean
* @param cacheKey the cache key for metadata access
* @return a proxy wrapping the bean, or the raw bean instance as-is
*/
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
参考
Spring 解决循环依赖为什么使用三级缓存,而不是二级缓存
Spring 三级缓存解决bean循环依赖,为何用三级缓存而非二级
其他网友的理解
并不是说二级缓存如果存在aop的话就无法将代理对象注入的问题,本质应该说是初始spring是没有解决循环引用问题的,设计原则是 bean 实例化、属性设置、初始化之后 再 生成aop对象,但是为了解决循环依赖但又尽量不打破这个设计原则的情况下,使用了存储了函数式接口的第三级缓存;
如果使用二级缓存的话,可以将aop的代理工作提前到 提前暴露实例的阶段执行; 也就是说所有的bean在创建过程中就先生成代理对象再初始化和其他工作; 但是这样的话,就和spring的aop的设计原则相驳,aop的实现需要与bean的正常生命周期的创建分离;
这样只有使用第三级缓存封装一个函数式接口对象到缓存中, 发生循环依赖时,触发代理类的生成;