這是 DefaultSingletonBeanRegistry 類的體系結構,由一個類一個責任的原則
- AliasRegistry : 提供別名注冊的接口
- SingletonBeanRegistry : ?提供單例bean注冊的接口
- ObjectFactory :?這個接口通常用于封裝一個通用的工廠,它只有一個方法getObject() ,它調用getObject()方法返回一個新的實例,一些在每次調用的目標對象(原型).
- DisposableBean :? 接口實現為beans要破壞釋放資源。它也只有一個方法destroy(),由一個破壞一個singleton的BeanFactory調用。
- SimpleAliasRegistry: 它簡單地實現了AliasRegistry接口。
- DefaultSingletonBeanRegistry: 它繼承SimpleAliasRegistry類和實現了SingletonBeanRegistry接口,因此這個類可以有別名注冊的功能和單例bean注冊的功能,并且他還支持注冊DisposableBean實例;它依賴ObjectFactory接口和DisposableBean接口(關閉注冊表時調用到了destroy方法)。
/**
* 共享bean實例的通用注冊表,實現了SingletonBeanRegistry. 允許注冊表中注冊的單例應該被所有調用者共享,通過bean名稱獲得。
*
* 還支持登記的DisposableBean實例,(這可能會或不能正確的注冊單例),關閉注冊表時destroyed.
* 可以注冊bean之間的依賴關系,執行適當的關閉順序。
*
*
* 這個類主要用作基類的BeanFactory實現, 提供基本的管理
* singleton bean 實例功能。
*
*/
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
SingletonBeanRegistry {
//內部標記為一個空的單例對象: 并發 Maps( 不支持空值 )作為標志值。
protected static final Object NULL_OBJECT = new Object();
// 日記用來記錄子類
protected final Log logger = LogFactory.getLog(getClass());
//是存放singleton對象的緩存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>();
// 是存放制造singleton的工廠對象的緩存
private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>();
//是存放singletonFactory 制造出來的 singleton 的緩存
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>();
//以上三個緩存是這個類存放單例bean的主要Map
//就是單例注冊表
private final Set<String> registeredSingletons = new LinkedHashSet<String>(
16);
//目前正在創建中的單例bean的名稱的集合
private final Set<String> singletonsCurrentlyInCreation = Collections
.synchronizedSet(new HashSet<String>());
//存放異常出現的相關的原因的集合
private Set<Exception> suppressedExceptions;
//標志,指示我們目前是否在銷毀單例中
private boolean singletonsCurrentlyInDestruction = false;
//存放一次性bean的緩存
private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
//外部bean與被包含在外部bean的所有內部bean集合包含關系的緩存
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>();
//指定bean與依賴指定bean的所有bean的依賴關系的緩存
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>();
//指定bean與創建這個bean所需要依賴的所有bean的依賴關系的緩存
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>();
// SingletonBeanRegistry接口的registerSingleton方法的實現
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的對象,則表示該名稱已被占用
if (oldObject != null) {
throw new IllegalStateException("Could not register object ["
+ singletonObject + "] under bean name '" + beanName
+ "': there is already object [" + oldObject
+ "] bound");
}
//若該名稱沒被占用,真正的注冊操作在這里實現
addSingleton(beanName, singletonObject);
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 因為singletonObjects類型是ConcurrentHashMap,并發Map不支持空值作為標志值,所以用NULL_OBJECT來代替
this.singletonObjects.put(beanName,
(singletonObject != null ? singletonObject : NULL_OBJECT));
// beanName已被注冊存放在singletonObjects緩存,那么singletonFactories不應該再持有名稱為beanName的工廠
this.singletonFactories.remove(beanName);
// beanName已被注冊存放在singletonObjects緩存,那么earlySingletonObjects不應該再持有名稱為beanName的bean。
this.earlySingletonObjects.remove(beanName);
// beanName放進單例注冊表中
this.registeredSingletons.add(beanName);
}
}
/**
* 添加 名稱為beanName的singletonFactory對象
*
*/
protected void addSingletonFactory(String beanName,
ObjectFactory singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
// 判斷singletonObjects內名字為beanName是否被占用,若沒有,進行注冊操作
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
// SingletonBeanRegistry接口的getSingleton方法的實現
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 如果singletonObjects指定beanName的對象是不存在的
if (singletonObject == null) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果earlySingletonObjects指定的beanName的對象是不存在的且allowEarlyReference是允許的
if (singletonObject == null && allowEarlyReference) {
ObjectFactory singletonFactory = this.singletonFactories
.get(beanName);
// 如果存在指定beanName的singletonFactory對象
if (singletonFactory != null) {
// singletonFactory創建指定的單例對象
singletonObject = singletonFactory.getObject();
// 這里可以看出earlySingletonObjects緩存應該是存放singletonFactory產生的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的對象
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 + "'");
}
// 單例對象創建前的回調,默認實現注冊正在創建的單例
beforeSingletonCreation(beanName);
// 判斷存儲異常相關原因的集合是否已存在
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
// 若沒有,剛創建異常集合的實例
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
// 由參數給定的singletonFactory創建singleton對象,getObject方法的具體實現由ObjectFactory的子類決定
singletonObject = singletonFactory.getObject();
} catch (BeanCreationException ex) {
// 如果異常被抓取,在這里將出現異常的原因拋出
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
// 結束前,將異常集合銷毀掉
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 單例創建之后的回調,默認的實現標志單例不要在創建了。
afterSingletonCreation(beanName);
}
// 注冊創建后的單例
addSingleton(beanName, singletonObject);
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
/**
* 注冊 發生在singeton bean 實例創建之間發生的異常
*/
protected void onSuppressedException(Exception ex) {
synchronized (this.singletonObjects) {
if (this.suppressedExceptions != null) {
this.suppressedExceptions.add(ex);
}
}
}
/**
* 移除名稱為beanName的單例,主要在四個集合中移除,
* 如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方法實現
public boolean containsSingleton(String beanName) {
return (this.singletonObjects.containsKey(beanName));
}
// singletonBeanRegistry接口的getSingletonNames方法實現
public String[] getSingletonNames() {
// 對singletonObjects加鎖,可能是為了防止registeredSingletons和singletonObjects出現不一致的問題
synchronized (this.singletonObjects) {
return StringUtils.toStringArray(this.registeredSingletons);
}
}
// singletonBeanRegistry接口的getSingletonCount方法實現
public int getSingletonCount() {
synchronized (this.singletonObjects) {
return this.registeredSingletons.size();
}
}
/**
* 單例對象創建前的回調,默認實現singletonsCurrentlyInCreation集合注冊正在創建的單例.
*
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
/**
* 單例創建之后的回調,默認實現singletonCurrentlyInCreation集合移除正在創建的單例
*
*/
protected void afterSingletonCreation(String beanName) {
if (!this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName
+ "' isn't currently in creation");
}
}
/**
* 返回 存放正在創建單例的集合是否包含指定名稱為beanName的單例存在
*
*/
public final boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
/**
* 一次性bean注冊,存放在disponsableBeans集合中
*
*/
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
/**
* 注冊兩個bean之間的控制關系,例如內部bean和包含其的外部bean之間
*
*/
public void registerContainedBean(String containedBeanName,
String containingBeanName) {
synchronized (this.containedBeanMap) {
// 從containedBeanMap緩存中查找外部bean名為containingBeanName的內部bean集合
Set<String> containedBeans = this.containedBeanMap
.get(containingBeanName);
// 如果沒有,剛新建一個存放內部bean的集合,并且存放在containedBeanMap緩存中
if (containedBeans == null) {
containedBeans = new LinkedHashSet<String>(8);
this.containedBeanMap.put(containingBeanName, containedBeans);
}
// 將名為containedBeanName的內部bean存放到內部bean集合
containedBeans.add(containedBeanName);
}
// 緊接著調用注冊內部bean和外部bean的依賴關系的方法
registerDependentBean(containedBeanName, containingBeanName);
}
/**
* 注冊給定bean的一個依賴bean,給定的bean銷毀之前被銷毀。
*
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
// 調用SimpleAliasRegistry的canonicalName方法,這方法是將參數beanName當做別名尋找到注冊名,并依此遞歸
String canonicalName = canonicalName(beanName);
synchronized (this.dependentBeanMap) {
// 從dependentBeanMap緩存中找到依賴名為canonicalName這個bean的 依賴bean集合
Set<String> dependentBeans = this.dependentBeanMap
.get(canonicalName);
// 如果為空,則新建一個依賴bean集合,并且存放到dependentBeanMap緩存中
if (dependentBeans == null) {
dependentBeans = new LinkedHashSet<String>(8);
this.dependentBeanMap.put(canonicalName, dependentBeans);
}
// 依賴bean集合添加參數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的被依賴關系
*/
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);
}
// 單例目前銷毀標志開始
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();
// 單例目前正在銷毀標志為結束
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實例
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,遞歸移除它的包含內部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;
}
}
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

