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; }