三級(jí)緩存
注意,三級(jí)緩存這個(gè)叫法是國(guó)內(nèi)的叫法饰及,Spring官方?jīng)]有任何三級(jí)緩存相關(guān)的叫法蔗坯,這個(gè)三級(jí)緩存的叫法來(lái)源于三個(gè)成員變量:
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry
/** Cache of singleton objects: bean name to bean instance. 一級(jí)緩存*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of early singleton objects: bean name to bean instance. 二級(jí)緩存*/
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Cache of singleton factories: bean name to ObjectFactory. 三級(jí)緩存*/
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
個(gè)人整理了一些資料,有需要的朋友可以直接點(diǎn)擊領(lǐng)取燎含。
對(duì)標(biāo)阿里P8的Java學(xué)習(xí)路線和資料
所以其實(shí)我們也應(yīng)該從實(shí)際使用意義上去理解這3個(gè)cache的意義宾濒,而不是只在名字上做文章,畢竟這3個(gè)名字很不合理屏箍。
Spring生成Bean時(shí)如何利用三級(jí)緩存
Spring在創(chuàng)建Bean的過(guò)程我們簡(jiǎn)化成我們關(guān)心的步驟:
- 實(shí)例化Bean
- 判斷作用域是否為單例绘梦,允許循環(huán)依賴,并且當(dāng)前bean正在創(chuàng)建赴魁,還沒(méi)有創(chuàng)建完成卸奉。如果都滿足條件,則調(diào)用addSingletonFactory將bean實(shí)例放入三級(jí)緩存中颖御,同時(shí)刪除二級(jí)緩存中相同的beanName元素榄棵,這里我們發(fā)現(xiàn)了一個(gè)秘密,單例對(duì)象只可能存在于三級(jí)緩存中的某一個(gè)潘拱,所以在添加到某一緩存中時(shí)疹鳄,一定會(huì)刪除其他2級(jí)緩存中的相同對(duì)象
- 調(diào)用populateBean方法進(jìn)行依賴注入
- 調(diào)用initializeBean方法完成對(duì)象初始化和AOP增強(qiáng)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory,添加到三級(jí)緩存方法
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);
}
}
}
其中涉及的流程可以從
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly)
這個(gè)方法開(kāi)始芦岂,這個(gè)方法是個(gè)關(guān)鍵的方法瘪弓,因?yàn)槔锩姘藙?chuàng)建Bean的流程,Spring在設(shè)計(jì)時(shí)禽最,將createBean放到了getBean的流程里
說(shuō)實(shí)話腺怯,這個(gè)方法太長(zhǎng),而且很多邏輯除非作者來(lái)講川无,否則很難自己將每一句代碼的意思都讀懂瓢喉,這里我們只挑感興趣的流程來(lái)看,
第一步我們看到第8行代碼舀透,
急切的檢查手動(dòng)注冊(cè)單例的單例緩存栓票,eager我們通常解釋為餓漢式,其實(shí)也有點(diǎn)樂(lè)觀的意思愕够,這里就直接到單例緩存中去取走贪,如果取到那肯定就是單例的,沒(méi)取到就需要?jiǎng)?chuàng)建惑芭。這種套路我們進(jìn)行實(shí)際編程時(shí)應(yīng)該學(xué)到坠狡,是個(gè)很常見(jiàn)的編程模式。
這里的邏輯是直接從單例池中獲取遂跟,如果獲取到了就可以直接返回bean逃沿,如果沒(méi)有獲取到就需要?jiǎng)?chuàng)建婴渡,在創(chuàng)建的邏輯里再去判斷是singleton還是prototype。
這里可以看到26行拋出了一個(gè)異常凯亮,原因是這個(gè)bean是一個(gè)prototype的边臼,而且發(fā)現(xiàn)這個(gè)bean已經(jīng)被加入到了正在創(chuàng)建的bean隊(duì)列中,只有一種可能就是假消,在創(chuàng)建他的時(shí)候柠并,他被加入到正在創(chuàng)建隊(duì)列中,他引用了別人富拗,在創(chuàng)建別人時(shí)臼予,別人引用了他,這種prototype的循環(huán)引用啃沪,Spring不提供解決方案粘拾,直接拋出異常,Spring希望這種情況下的循環(huán)引用由應(yīng)用自己修改邏輯创千。
下面我們可以看到82半哟、100、118行就是真正的實(shí)例化bean的地方签餐,org.springframework.beans.factory.support.AbstractBeanFactory#createBean()寓涨,這個(gè)方法在AbstractBeanFactory中是抽象的空方法,交給了子類去實(shí)現(xiàn)氯檐,由于createBean中涉及了三級(jí)緩存相關(guān)的邏輯所以我們不得不在看看相關(guān)的源碼戒良。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
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 + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
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);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
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.
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);
}
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);
}
else {
String scopeName = mbd.getScope();
final 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 ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
如下就是createBean()方法的源碼,老長(zhǎng)了
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
很不幸冠摄,方法雖長(zhǎng)糯崎,核心卻被封裝到了另一個(gè)方法doCreateBean()中,看看41行河泳,我們又要去粘貼源碼了.......
@Override
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.
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 {
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);
}
}
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean()
看第10行沃呢,是實(shí)例化對(duì)象,可以理解為給對(duì)象分配內(nèi)存
看第41行拆挥,就是加入第三級(jí)緩存薄霜,終于找到這個(gè)關(guān)鍵點(diǎn)了,注意這里有個(gè)非常重要的點(diǎn)纸兔,就是傳遞的是一個(gè)lambda表達(dá)式惰瓜,也就是一個(gè)函數(shù),也就是說(shuō)三級(jí)緩存里面直接存儲(chǔ)的是并不一個(gè)bean汉矿,想要從三級(jí)緩存里拿出bean崎坊,需要調(diào)用一下這個(gè)函數(shù),調(diào)用時(shí)機(jī)是在getSingleton()函數(shù)觸發(fā)的洲拇,也就是說(shuō)這里只是關(guān)聯(lián)上了方法奈揍,不會(huì)去調(diào)用曲尸。
看第47行,是填充屬性的方法男翰,這個(gè)方法里會(huì)觸發(fā)引用對(duì)象的創(chuàng)建另患,包括循環(huán)依賴的對(duì)象的創(chuàng)建
看第48行,是后置處理邏輯的地方
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
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.
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");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
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) {
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 {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
這個(gè)就是屬性裝配的方法奏篙,里面涉及了引用對(duì)象的創(chuàng)建
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean()
看org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues()這個(gè)方法里面就知道。
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;
}
}
}
}
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) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
下面就是將bean對(duì)應(yīng)的ObjectFactory添加到三級(jí)緩存的代碼:
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);
}
}
}
這里需要注意的是迫淹,調(diào)用加入三級(jí)緩存的方法時(shí)秘通,傳遞的實(shí)參是什么下面這個(gè)函數(shù),相當(dāng)于存入三級(jí)緩存保留了一段后置邏輯敛熬,等到調(diào)用getSingleton()是就會(huì)觸發(fā)肺稀,為什么要這么設(shè)計(jì)呢?為什么不在存入的時(shí)候直接就執(zhí)行了這段邏輯应民?
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
我們關(guān)心的是什么時(shí)候取出來(lái)话原,取出來(lái)的時(shí)機(jī)是getSingleton()方法,這里有2個(gè)方法:
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)
前者是用于檢查單例池中是否有bean诲锹,同時(shí)會(huì)提升三級(jí)緩存到二級(jí)緩存繁仁,這么做的原因要回頭看doGetBean()方法的邏輯,每一個(gè)doGetBean()的方法最前面都會(huì)調(diào)用第一個(gè)getSingleton()方法归园,一般而言黄虱,就2種情況,一級(jí)緩存中找到庸诱,或者一級(jí)緩存中沒(méi)找到捻浦,三級(jí)緩存中找到,此時(shí)是循環(huán)依賴的情況桥爽,那么此時(shí)Spring就要提升依賴bean到二級(jí)緩存朱灿。后者用于createBean,因?yàn)榈诙€(gè)參數(shù)傳遞的是createBean()函數(shù)钠四,更重要的是他在里面調(diào)用了盗扒,看第39行的singletonFactory.getObject()會(huì)觸發(fā)createBean動(dòng)作。然后后面有一個(gè)加入一級(jí)緩存的動(dòng)作缀去。
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
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;
}
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);
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 {
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;
}
}
流程總結(jié):
前提:我們將2個(gè)重載的getSingleton()方法依次命名為getSingleton1()和getSingleton2()环疼,具體區(qū)別看上面講解
在Spring中,將createBean的動(dòng)作封裝在了doGetBean()動(dòng)作里朵耕,doGetBean()每次獲取bean都要先從單例池中去拿單例:getSingleton1()炫隶,注意,getSingleton1()方法是有一些邏輯的阎曹,不僅僅是一個(gè)get動(dòng)作伪阶,他有一個(gè)執(zhí)行三級(jí)緩存中ObjectFactory生產(chǎn)對(duì)象的動(dòng)作煞檩,這里有需要的話,會(huì)產(chǎn)生代理對(duì)象栅贴,并將三級(jí)緩存提升至二級(jí)緩存斟湃。當(dāng)然,如果getSingleton1()方法返回的是null檐薯,doGetBean()將會(huì)調(diào)用getSingleton2()凝赛,那么將會(huì)觸發(fā)doCreateBean()方法,doCreateBean()方法是singleton和prototype類型的bean通用的方法坛缕,doCreateBean()首先實(shí)例化bean墓猎,然后判斷是否是singleton,是的話就加入到三級(jí)緩存赚楚,然后進(jìn)行屬性填充和初始化回調(diào)毙沾,然后根據(jù)條件調(diào)用getSintleton1(),同時(shí)接著getSingleton2()方法將會(huì)把創(chuàng)建的對(duì)象加入到1級(jí)緩存宠页,注意這個(gè)順序左胞,就這樣,完成對(duì)象的創(chuàng)建了举户。
動(dòng)態(tài)代理+循環(huán)依賴
這里還有個(gè)更加重要場(chǎng)景烤宙,就是循環(huán)依賴+動(dòng)態(tài)代理。這種場(chǎng)景在實(shí)際使用中是會(huì)產(chǎn)生的俭嘁,如果僅僅是循環(huán)依賴或是僅僅是動(dòng)態(tài)代理门烂,這個(gè)很好理解。假設(shè)這里有A兄淫、B2個(gè)對(duì)象互相依賴且A需要生成代理對(duì)象屯远,假設(shè)先實(shí)例化A,那么他們實(shí)例化的流程是:
實(shí)例化A捕虽,將A加入三級(jí)緩存慨丐,填充A屬性,發(fā)現(xiàn)B
實(shí)例化B泄私,將B加入三級(jí)緩存房揭,填充B屬性,發(fā)現(xiàn)A
從三級(jí)緩存中取到A晌端,然后產(chǎn)生A的代理對(duì)象捅暴,并將A的代理對(duì)象升級(jí)到2級(jí)緩存,將B升級(jí)到1級(jí)緩存等咧纠,完成B的創(chuàng)建
將A升級(jí)到一級(jí)緩存等操作蓬痒,完成A的創(chuàng)建
這段代碼是上面org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean()中的一段,他存入三級(jí)緩存的這個(gè)函數(shù)漆羔,就包含了獲取代理對(duì)象的邏輯梧奢。
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
事實(shí)是動(dòng)態(tài)代理+循環(huán)依賴一般情況下狱掂,Spring會(huì)報(bào)一個(gè)錯(cuò)誤:
Error creating bean with name 'classA': Bean with name 'classA' has been injected into other beans [classB] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
如果加上一個(gè)懶加載就能解決問(wèn)題。
單例懶加載
一般說(shuō)懶加載都是說(shuō)單例的亲轨,單純的一個(gè)沒(méi)有引用其他對(duì)象趋惨,也沒(méi)有被其他對(duì)象引用的對(duì)象似乎比較好理解,就是掃描到對(duì)象了惦蚊,判斷一下是否是延遲加載器虾,是的話就不進(jìn)行實(shí)例化后后續(xù)初始化。這個(gè)好理解蹦锋,主要是bean都是互相引用的兆沙,如果懶加載bean和非懶加載bean之間互相引用了,我們需要搞清楚現(xiàn)象晕粪。這里有個(gè)大膽的猜測(cè):
1挤悉、懶加載bean引用非懶加載bean時(shí)渐裸,非懶加載bean照常進(jìn)行初始化
2巫湘、非懶加載bean引用懶加載bean時(shí),懶加載bean也要照常進(jìn)行初始化
最后
感謝你看到這里昏鹃,文章有什么不足還請(qǐng)指正尚氛,覺(jué)得文章對(duì)你有幫助的話記得給我點(diǎn)個(gè)贊,每天都會(huì)分享java相關(guān)技術(shù)文章或行業(yè)資訊洞渤,歡迎大家關(guān)注和轉(zhuǎn)發(fā)文章阅嘶!