這是 DefaultSingletonBeanRegistry 類的體系結(jié)構(gòu),由一個(gè)類一個(gè)責(zé)任的原則
- AliasRegistry : 提供別名注冊(cè)的接口
- SingletonBeanRegistry : ?提供單例bean注冊(cè)的接口
- ObjectFactory :?這個(gè)接口通常用于封裝一個(gè)通用的工廠,它只有一個(gè)方法getObject() ,它調(diào)用getObject()方法返回一個(gè)新的實(shí)例,一些在每次調(diào)用的目標(biāo)對(duì)象(原型).
- DisposableBean :? 接口實(shí)現(xiàn)為beans要破壞釋放資源。它也只有一個(gè)方法destroy(),由一個(gè)破壞一個(gè)singleton的BeanFactory調(diào)用。
- SimpleAliasRegistry: 它簡單地實(shí)現(xiàn)了AliasRegistry接口。
- DefaultSingletonBeanRegistry: 它繼承SimpleAliasRegistry類和實(shí)現(xiàn)了SingletonBeanRegistry接口,因此這個(gè)類可以有別名注冊(cè)的功能和單例bean注冊(cè)的功能,并且他還支持注冊(cè)DisposableBean實(shí)例;它依賴ObjectFactory接口和DisposableBean接口(關(guān)閉注冊(cè)表時(shí)調(diào)用到了destroy方法)。
/**
* 共享bean實(shí)例的通用注冊(cè)表,實(shí)現(xiàn)了SingletonBeanRegistry. 允許注冊(cè)表中注冊(cè)的單例應(yīng)該被所有調(diào)用者共享,通過bean名稱獲得。
*
* 還支持登記的DisposableBean實(shí)例,(這可能會(huì)或不能正確的注冊(cè)單例),關(guān)閉注冊(cè)表時(shí)destroyed.
* 可以注冊(cè)bean之間的依賴關(guān)系,執(zhí)行適當(dāng)?shù)年P(guān)閉順序。
*
*
* 這個(gè)類主要用作基類的BeanFactory實(shí)現(xiàn), 提供基本的管理
* singleton bean 實(shí)例功能。
*
*/
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
SingletonBeanRegistry {
//內(nèi)部標(biāo)記為一個(gè)空的單例對(duì)象: 并發(fā) Maps( 不支持空值 )作為標(biāo)志值。
protected static final Object NULL_OBJECT = new Object();
// 日記用來記錄子類
protected final Log logger = LogFactory.getLog(getClass());
//是存放singleton對(duì)象的緩存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>();
// 是存放制造singleton的工廠對(duì)象的緩存
private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>();
//是存放singletonFactory 制造出來的 singleton 的緩存
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>();
//以上三個(gè)緩存是這個(gè)類存放單例bean的主要Map
//就是單例注冊(cè)表
private final Set<String> registeredSingletons = new LinkedHashSet<String>(
16);
//目前正在創(chuàng)建中的單例bean的名稱的集合
private final Set<String> singletonsCurrentlyInCreation = Collections
.synchronizedSet(new HashSet<String>());
//存放異常出現(xiàn)的相關(guān)的原因的集合
private Set<Exception> suppressedExceptions;
//標(biāo)志,指示我們目前是否在銷毀單例中
private boolean singletonsCurrentlyInDestruction = false;
//存放一次性bean的緩存
private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
//外部bean與被包含在外部bean的所有內(nèi)部bean集合包含關(guān)系的緩存
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>();
//指定bean與依賴指定bean的所有bean的依賴關(guān)系的緩存
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>();
//指定bean與創(chuàng)建這個(gè)bean所需要依賴的所有bean的依賴關(guān)系的緩存
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>();
// SingletonBeanRegistry接口的registerSingleton方法的實(shí)現(xiàn)
public void registerSingleton(String beanName, Object singletonObject)
throws IllegalStateException {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
//如果singletonObjects緩存找到有指定名稱為beanName的對(duì)象,則表示該名稱已被占用
if (oldObject != null) {
throw new IllegalStateException("Could not register object ["
+ singletonObject + "] under bean name '" + beanName
+ "': there is already object [" + oldObject
+ "] bound");
}
//若該名稱沒被占用,真正的注冊(cè)操作在這里實(shí)現(xiàn)
addSingleton(beanName, singletonObject);
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 因?yàn)閟ingletonObjects類型是ConcurrentHashMap,并發(fā)Map不支持空值作為標(biāo)志值,所以用NULL_OBJECT來代替
this.singletonObjects.put(beanName,
(singletonObject != null ? singletonObject : NULL_OBJECT));
// beanName已被注冊(cè)存放在singletonObjects緩存,那么singletonFactories不應(yīng)該再持有名稱為beanName的工廠
this.singletonFactories.remove(beanName);
// beanName已被注冊(cè)存放在singletonObjects緩存,那么earlySingletonObjects不應(yīng)該再持有名稱為beanName的bean。
this.earlySingletonObjects.remove(beanName);
// beanName放進(jìn)單例注冊(cè)表中
this.registeredSingletons.add(beanName);
}
}
/**
* 添加 名稱為beanName的singletonFactory對(duì)象
*
*/
protected void addSingletonFactory(String beanName,
ObjectFactory singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
// 判斷singletonObjects內(nèi)名字為beanName是否被占用,若沒有,進(jìn)行注冊(cè)操作
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
// SingletonBeanRegistry接口的getSingleton方法的實(shí)現(xiàn)
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 如果singletonObjects指定beanName的對(duì)象是不存在的
if (singletonObject == null) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果earlySingletonObjects指定的beanName的對(duì)象是不存在的且allowEarlyReference是允許的
if (singletonObject == null && allowEarlyReference) {
ObjectFactory singletonFactory = this.singletonFactories
.get(beanName);
// 如果存在指定beanName的singletonFactory對(duì)象
if (singletonFactory != null) {
// singletonFactory創(chuàng)建指定的單例對(duì)象
singletonObject = singletonFactory.getObject();
// 這里可以看出earlySingletonObjects緩存應(yīng)該是存放singletonFactory產(chǎn)生的singleton
this.earlySingletonObjects.put(beanName,
singletonObject);
// 這里表示指定的beanName已被占用,所以要在singletonFactories移除該名稱
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
// 如果singetonObjects緩存不存在名稱為beanName的對(duì)象
if (singletonObject == null) {
// 如果目前在銷毀singellton
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(
beanName,
"Singleton bean creation not allowed while the 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 + "'");
}
// 單例對(duì)象創(chuàng)建前的回調(diào),默認(rèn)實(shí)現(xiàn)注冊(cè)正在創(chuàng)建的單例
beforeSingletonCreation(beanName);
// 判斷存儲(chǔ)異常相關(guān)原因的集合是否已存在
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
// 若沒有,剛創(chuàng)建異常集合的實(shí)例
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
// 由參數(shù)給定的singletonFactory創(chuàng)建singleton對(duì)象,getObject方法的具體實(shí)現(xiàn)由ObjectFactory的子類決定
singletonObject = singletonFactory.getObject();
} catch (BeanCreationException ex) {
// 如果異常被抓取,在這里將出現(xiàn)異常的原因拋出
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
// 結(jié)束前,將異常集合銷毀掉
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 單例創(chuàng)建之后的回調(diào),默認(rèn)的實(shí)現(xiàn)標(biāo)志單例不要在創(chuàng)建了。
afterSingletonCreation(beanName);
}
// 注冊(cè)創(chuàng)建后的單例
addSingleton(beanName, singletonObject);
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
/**
* 注冊(cè) 發(fā)生在singeton bean 實(shí)例創(chuàng)建之間發(fā)生的異常
*/
protected void onSuppressedException(Exception ex) {
synchronized (this.singletonObjects) {
if (this.suppressedExceptions != null) {
this.suppressedExceptions.add(ex);
}
}
}
/**
* 移除名稱為beanName的單例,主要在四個(gè)集合中移除,
* 如singletonObjects,singletonFactories,earlySingletonObjects
* ,registeredSingletons
*
*/
protected void removeSingleton(String beanName) {
synchronized (this.singletonObjects) {
this.singletonObjects.remove(beanName);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.remove(beanName);
}
}
// singletonBeanRegistry接口的containsSingleton方法實(shí)現(xiàn)
public boolean containsSingleton(String beanName) {
return (this.singletonObjects.containsKey(beanName));
}
// singletonBeanRegistry接口的getSingletonNames方法實(shí)現(xiàn)
public String[] getSingletonNames() {
// 對(duì)singletonObjects加鎖,可能是為了防止registeredSingletons和singletonObjects出現(xiàn)不一致的問題
synchronized (this.singletonObjects) {
return StringUtils.toStringArray(this.registeredSingletons);
}
}
// singletonBeanRegistry接口的getSingletonCount方法實(shí)現(xiàn)
public int getSingletonCount() {
synchronized (this.singletonObjects) {
return this.registeredSingletons.size();
}
}
/**
* 單例對(duì)象創(chuàng)建前的回調(diào),默認(rèn)實(shí)現(xiàn)singletonsCurrentlyInCreation集合注冊(cè)正在創(chuàng)建的單例.
*
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
/**
* 單例創(chuàng)建之后的回調(diào),默認(rèn)實(shí)現(xiàn)singletonCurrentlyInCreation集合移除正在創(chuàng)建的單例
*
*/
protected void afterSingletonCreation(String beanName) {
if (!this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName
+ "' isn't currently in creation");
}
}
/**
* 返回 存放正在創(chuàng)建單例的集合是否包含指定名稱為beanName的單例存在
*
*/
public final boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
/**
* 一次性bean注冊(cè),存放在disponsableBeans集合中
*
*/
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
/**
* 注冊(cè)兩個(gè)bean之間的控制關(guān)系,例如內(nèi)部bean和包含其的外部bean之間
*
*/
public void registerContainedBean(String containedBeanName,
String containingBeanName) {
synchronized (this.containedBeanMap) {
// 從containedBeanMap緩存中查找外部bean名為containingBeanName的內(nèi)部bean集合
Set<String> containedBeans = this.containedBeanMap
.get(containingBeanName);
// 如果沒有,剛新建一個(gè)存放內(nèi)部bean的集合,并且存放在containedBeanMap緩存中
if (containedBeans == null) {
containedBeans = new LinkedHashSet<String>(8);
this.containedBeanMap.put(containingBeanName, containedBeans);
}
// 將名為containedBeanName的內(nèi)部bean存放到內(nèi)部bean集合
containedBeans.add(containedBeanName);
}
// 緊接著調(diào)用注冊(cè)內(nèi)部bean和外部bean的依賴關(guān)系的方法
registerDependentBean(containedBeanName, containingBeanName);
}
/**
* 注冊(cè)給定bean的一個(gè)依賴bean,給定的bean銷毀之前被銷毀。
*
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
// 調(diào)用SimpleAliasRegistry的canonicalName方法,這方法是將參數(shù)beanName當(dāng)做別名尋找到注冊(cè)名,并依此遞歸
String canonicalName = canonicalName(beanName);
synchronized (this.dependentBeanMap) {
// 從dependentBeanMap緩存中找到依賴名為canonicalName這個(gè)bean的 依賴bean集合
Set<String> dependentBeans = this.dependentBeanMap
.get(canonicalName);
// 如果為空,則新建一個(gè)依賴bean集合,并且存放到dependentBeanMap緩存中
if (dependentBeans == null) {
dependentBeans = new LinkedHashSet<String>(8);
this.dependentBeanMap.put(canonicalName, dependentBeans);
}
// 依賴bean集合添加參數(shù)2指定的dependentBeanName
dependentBeans.add(dependentBeanName);
}
synchronized (this.dependenciesForBeanMap) {
// 從dependenciesForBeanMap緩存中找到dependentBeanName要依賴的所有bean集合
Set<String> dependenciesForBean = this.dependenciesForBeanMap
.get(dependentBeanName);
if (dependenciesForBean == null) {
dependenciesForBean = new LinkedHashSet<String>(8);
this.dependenciesForBeanMap.put(dependentBeanName,
dependenciesForBean);
}
dependenciesForBean.add(canonicalName);
}
}
/**
* 確定是否還存在名為beanName的被依賴關(guān)系
*/
protected boolean hasDependentBean(String beanName) {
return this.dependentBeanMap.containsKey(beanName);
}
/**
* 返回依賴于指定的bean的所有bean的名稱,如果有的話。
*
*/
public String[] getDependentBeans(String beanName) {
Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
return new String[0];
}
return StringUtils.toStringArray(dependentBeans);
}
/**
* 返回指定的bean依賴于所有的bean的名稱,如果有的話。
*
*/
public String[] getDependenciesForBean(String beanName) {
Set<String> dependenciesForBean = this.dependenciesForBeanMap
.get(beanName);
// 如果沒有的話返回new String[0]而不是null
if (dependenciesForBean == null) {
return new String[0];
}
return dependenciesForBean.toArray(new String[dependenciesForBean
.size()]);
}
// 銷毀單例
public void destroySingletons() {
if (logger.isInfoEnabled()) {
logger.info("Destroying singletons in " + this);
}
// 單例目前銷毀標(biāo)志開始
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
// 銷毀disponsableBeans緩存中所有單例bean
synchronized (this.disposableBeans) {
String[] disposableBeanNames = StringUtils
.toStringArray(this.disposableBeans.keySet());
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
}
// containedBeanMap緩存清空,dependentBeanMap緩存清空,dependenciesForBeanMap緩存清空
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
// singeltonObjects緩存清空,singletonFactories緩存清空,earlySingletonObjects緩存清空,registeredSingletons緩存清空
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
// 單例目前正在銷毀標(biāo)志為結(jié)束
this.singletonsCurrentlyInDestruction = false;
}
}
public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
removeSingleton(beanName);
// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
disposableBean = (DisposableBean) this.disposableBeans
.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
protected void destroyBean(String beanName, DisposableBean bean) {
// Trigger destruction of dependent beans first...
// 這段代碼告訴我們先移除要銷毀依賴bean
Set<String> dependencies = this.dependentBeanMap.remove(beanName);
if (dependencies != null) {
if (logger.isDebugEnabled()) {
logger.debug("Retrieved dependent beans for bean '" + beanName
+ "': " + dependencies);
}
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
// Actually destroy the bean now...
// 銷毀bean實(shí)例
if (bean != null) {
try {
bean.destroy();
} catch (Throwable ex) {
logger.error("Destroy method on bean with name '" + beanName
+ "' threw an exception", ex);
}
}
// Trigger destruction of contained beans...
// 從containedBeanMap緩存中移除要銷毀的bean,遞歸移除它的包含內(nèi)部bean集合
Set<String> containedBeans = this.containedBeanMap.remove(beanName);
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// Remove destroyed bean from other beans' dependencies.
// 從其它bean的依賴bean集合中移除要銷毀的bean
synchronized (this.dependentBeanMap) {
for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap
.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Set<String>> entry = it.next();
Set<String> dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// Remove destroyed bean's prepared dependency information.
// 最后 從dependenciesForBeanMap緩存中移除要銷毀的bean
this.dependenciesForBeanMap.remove(beanName);
}
/**
* Expose the singleton mutex to subclasses.
* <p>
* Subclasses should synchronize on the given Object if they perform any
* sort of extended singleton creation phase. In particular, subclasses
* should <i>not</i> have their own mutexes involved in singleton creation,
* to avoid the potential for deadlocks in lazy-init situations.
*/
protected final Object getSingletonMutex() {
return this.singletonObjects;
}
}
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

