DefaultSingletonBeanRegistry類繼承了SimpleAliasRegistry以及實現了SingletonBeanRegistry的接口。處理Bean的註冊,銷燬,以及依賴關係的註冊和銷燬。segmentfault
截取部分數組
// 單例對象的緩存:從beanname到bean實例 private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); // 單例工廠的緩存:從beanname到ObjectFactory private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16); // 早期單例對象的緩存:從beanname到bean實例 private final Map<String, Object> earlySingletonObjects = new HashMap<>(16); // 一組已註冊的單例,包含按註冊順序排列的beanname private final Set<String> registeredSingletons = new LinkedHashSet<>(256); // 正在建立的單例的beanName的集合 private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); // 當前不檢查的bean的集合 private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); // 異常集合 private Set<Exception> suppressedExceptions; // 當前是否在銷燬bean中 private boolean singletonsCurrentlyInDestruction = false; // 一次性bean實例 private final Map<String, Object> disposableBeans = new LinkedHashMap<>(); // 內部bean和外部bean之間關係 private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16); // 指定bean與依賴指定bean的集合,好比bcd依賴a,那麼就是key爲a,bcd爲value private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64); // 指定bean與指定bean依賴的集合,好比a依賴bcd,那麼就是key爲a,bcd爲value private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
經過bean的名稱和對象進行註冊。緩存
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { Assert.notNull(beanName, "Bean name must not be null"); Assert.notNull(singletonObject, "Singleton object must not be null"); synchronized (this.singletonObjects) { Object oldObject = this.singletonObjects.get(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); } }
單例加入到緩存中app
protected void addSingleton(String beanName, Object singletonObject) { synchronized (this.singletonObjects) { // 加入單例對象的緩存 this.singletonObjects.put(beanName, singletonObject); // 既然加入了單例對象的緩存,那singletonFactories和earlySingletonObjects就再也不持有 this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); // 加入已註冊的bean this.registeredSingletons.add(beanName); } }
//增長單例工程的單例,取單例的時候調用getObject方法 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); } } }
public Object getSingleton(String beanName) { // 容許早期依賴 return getSingleton(beanName, true); } 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); //allowEarlyReference容許是否從singletonFactories讀取 if (singletonObject == null && allowEarlyReference) { // 某些方法提早初始化的時候會調用addSingletonFactory,把ObjectFactory緩存在singletonFactories中 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { //若是singletonFactories有,調用getObject方法返回 singletonObject = singletonFactory.getObject(); // singletonFactories產生的對象放入earlySingletonObjects中 this.earlySingletonObjects.put(beanName, singletonObject); // 已經產生過一次對象了,因此就不能再用了,後面直接用earlySingletonObjects獲取 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) { // 當前在銷燬bean,不能建立 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 { // 經過ObjectFactory的getObject建立bean,實際是回調createBean方法 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. // 有多是其餘方式建立的bean 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) { // 是新建立的bean,就加入到緩存中並移除其餘緩存,若是是其餘方式建立的bean,說明已經加入過緩存了,這邊再也不加入 addSingleton(beanName, singletonObject); } } return singletonObject; } }
註冊過程當中發生的異常,加入到異常集合ide
protected void onSuppressedException(Exception ex) { synchronized (this.singletonObjects) { if (this.suppressedExceptions != null) { this.suppressedExceptions.add(ex); } } }
移除單例,這四個同時移除this
protected void removeSingleton(String beanName) { synchronized (this.singletonObjects) { this.singletonObjects.remove(beanName); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.remove(beanName); } }
singletonObjects、registeredSingletons的信息讀取spa
@Override public boolean containsSingleton(String beanName) { // 是否已經緩存過 return this.singletonObjects.containsKey(beanName); } @Override public String[] getSingletonNames() { //獲取已經註冊過的bean synchronized (this.singletonObjects) { return StringUtils.toStringArray(this.registeredSingletons); } } @Override public int getSingletonCount() { // 獲取單例的個數 synchronized (this.singletonObjects) { return this.registeredSingletons.size(); } }
設置不檢查的beanNamedebug
public void setCurrentlyInCreation(String beanName, boolean inCreation) { Assert.notNull(beanName, "Bean name must not be null"); if (!inCreation) { this.inCreationCheckExclusions.add(beanName); } else { this.inCreationCheckExclusions.remove(beanName); } }
是否當前建立的beancode
public boolean isCurrentlyInCreation(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); // 若是這個beanName在不檢查集合裏,返回false,說明當前沒有建立 // 若是這個beanName要檢查,那就要返回是不是正在建立的bean return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName)); } protected boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName); } public boolean isSingletonCurrentlyInCreation(String beanName) { return this.singletonsCurrentlyInCreation.contains(beanName); }
protected void beforeSingletonCreation(String beanName) { // 若是這個beanName要檢查,看看add的時候返回什麼,若是返回false,說明已經在建立了,拋異常 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } } protected void afterSingletonCreation(String beanName) { // 若是這個beanName要檢查,看看remove返回什麼,若是返回false,說明已經建立完了。 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) { throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation"); } }
註冊一次性bean實例orm
public void registerDisposableBean(String beanName, DisposableBean bean) { synchronized (this.disposableBeans) { this.disposableBeans.put(beanName, bean); } }
public void registerContainedBean(String containedBeanName, String containingBeanName) { synchronized (this.containedBeanMap) { // 若是沒有key爲containingBeanName的value,說明內部bean集合爲空,則初始化一個 Set<String> containedBeans = this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8)); // 若是已經存在了對應關係,則直接返回,不存在,就添加對應關係 if (!containedBeans.add(containedBeanName)) { return; } } registerDependentBean(containedBeanName, containingBeanName); }
canonicalName方法是屬於SimpleAliasRegistry的方法。
public void registerDependentBean(String beanName, String dependentBeanName) { String canonicalName = canonicalName(beanName); synchronized (this.dependentBeanMap) { Set<String> dependentBeans = this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8)); // 若是已經存在了對應關係,則直接返回,不存在,就添加對應關係 if (!dependentBeans.add(dependentBeanName)) { return; } } synchronized (this.dependenciesForBeanMap) { Set<String> dependenciesForBean = this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8)); // 添加對應關係 dependenciesForBean.add(canonicalName); } }
dependentBeanName是否依賴beanName
protected boolean isDependent(String beanName, String dependentBeanName) { synchronized (this.dependentBeanMap) { return isDependent(beanName, dependentBeanName, null); } } private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) { if (alreadySeen != null && alreadySeen.contains(beanName)) { return false; } String canonicalName = canonicalName(beanName); Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName); // 爲空,說明沒有bean依賴beanName,直接返回false if (dependentBeans == null) { return false; } // 有其餘bean依賴beanName,且包含了dependentBeanName,返回true if (dependentBeans.contains(dependentBeanName)) { return true; } // 有其餘bean依賴beanName,可是不包含dependentBeanName for (String transitiveDependency : dependentBeans) { if (alreadySeen == null) { alreadySeen = new HashSet<>(); } alreadySeen.add(beanName); // 是否有循環依賴 if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { return true; } } return false; }
是否有其餘對象依賴指定bean
protected boolean hasDependentBean(String beanName) { return this.dependentBeanMap.containsKey(beanName); }
返回依賴指定bean的數組
public String[] getDependentBeans(String beanName) { Set<String> dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { return new String[0]; } synchronized (this.dependentBeanMap) { return StringUtils.toStringArray(dependentBeans); } }
返回指定bean,依賴其餘bean的數組
public String[] getDependenciesForBean(String beanName) { Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName); if (dependenciesForBean == null) { return new String[0]; } synchronized (this.dependenciesForBeanMap) { return StringUtils.toStringArray(dependenciesForBean); } }
銷燬單例
public void destroySingletons() { if (logger.isTraceEnabled()) { logger.trace("Destroying singletons in " + this); } // 設置當前正在銷燬 synchronized (this.singletonObjects) { this.singletonsCurrentlyInDestruction = true; } String[] disposableBeanNames; synchronized (this.disposableBeans) { disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet()); } // 銷燬disposableBeans中的全部bean for (int i = disposableBeanNames.length - 1; i >= 0; i--) { destroySingleton(disposableBeanNames[i]); } // 清空containedBeanMap、dependentBeanMap、dependenciesForBeanMap this.containedBeanMap.clear(); this.dependentBeanMap.clear(); this.dependenciesForBeanMap.clear(); // 清除單例緩存 clearSingletonCache(); }
清除單例緩存
protected void clearSingletonCache() { synchronized (this.singletonObjects) { this.singletonObjects.clear(); this.singletonFactories.clear(); this.earlySingletonObjects.clear(); this.registeredSingletons.clear(); // 清除完後,標誌恢復爲false this.singletonsCurrentlyInDestruction = false; } }
銷燬單例bean
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) { // 從disposableBeans移除,若是有beanName對應的對象,返回這個對象 disposableBean = (DisposableBean) this.disposableBeans.remove(beanName); } // 消耗bean destroyBean(beanName, disposableBean); }
消耗bean
protected void destroyBean(String beanName, @Nullable DisposableBean bean) { // Trigger destruction of dependent beans first... Set<String> dependencies; // 移除依賴當前beanName的bean synchronized (this.dependentBeanMap) { // Within full synchronization in order to guarantee a disconnected Set // 獲取依賴當前beanName的bean dependencies = this.dependentBeanMap.remove(beanName); } if (dependencies != null) { if (logger.isTraceEnabled()) { logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies); } // 移除依賴當前beanName的bean for (String dependentBeanName : dependencies) { destroySingleton(dependentBeanName); } } // Actually destroy the bean now... if (bean != null) { try { // 銷燬bean bean.destroy(); } catch (Throwable ex) { if (logger.isInfoEnabled()) { logger.info("Destroy method on bean with name '" + beanName + "' threw an exception", ex); } } } // Trigger destruction of contained beans... // 異常beanName的對應關係的bean Set<String> containedBeans; synchronized (this.containedBeanMap) { // Within full synchronization in order to guarantee a disconnected Set containedBeans = this.containedBeanMap.remove(beanName); } if (containedBeans != null) { for (String containedBeanName : containedBeans) { destroySingleton(containedBeanName); } } // Remove destroyed bean from other beans' dependencies. // 這個對象被其餘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); //若是除了當前的beanName,沒有其餘依賴了,直接刪除 if (dependenciesToClean.isEmpty()) { it.remove(); } } } // Remove destroyed bean's prepared dependency information. // 移除當前bean與依賴其餘bean的關係 this.dependenciesForBeanMap.remove(beanName); }
用於加鎖操做,返回singletonObjects,經過方法暴露這個對象。
public final Object getSingletonMutex() { return this.singletonObjects; }