小工具知识网

当前位置: 首页 > 行业知识 > DefaultSingletonBeanRegistry学习

行业知识

DefaultSingletonBeanRegistry学习

2026-11-10 23:25:52 来源:互联网转载

简介

DefaultSingletonBeanRegistry ��� Spring 框架中的一个核心类,它负责在 Spring 的应用上下文中管理单例 bean 的生命周期。该类实现了 SingletonBeanRegistry 接口,提供了注册、获取、销毁单例 bean 的功能。

()

在 Spring 的应用上下文中,bean 默认是单例的,这意味着 Spring 容器会确保每个 bean 的实例在容器中只被创建一次,并且这个实例会被所有的请求共享。DefaultSingletonBeanRegistry 就是负责实现这种单例行为的核心组件。

以下是 DefaultSingletonBeanRegistry 类的一些关键功能:

()
  • 注册 Bean: 通过 registerSingleton 方法,可以将一个新的单例 bean 注册到注册表中。这个方法会先检查注册表中是否已经存在该 bean,如果存在则不会重复注册,否则会创建一个新的 bean 实例并将其注册到注册表中。
  • 获取 Bean: 通过 getSingleton 方法,可以从注册表中获取一个已经注册的单例 bean。如果 bean 还没有被创建,这个方法会先创建 bean 的实例,然后将其返回。
  • 销毁 Bean: 当应用上下文关闭时,所有的单例 bean 都需要被销毁以释放资源。DefaultSingletonBeanRegistry 提供了 destroyBean 方法来销毁一个单例 bean。这个方法会先调用 bean 的 destroy 方法(如果存在的话),然后从注册表中移除该 bean。

    除了上述基本功能外,DefaultSingletonBeanRegistry 还提供了一些其他的功能,比如允许用户自定义 bean 的创建和销毁过程、支持 bean 的延迟初始化等。

    需要注意的是,虽然 DefaultSingletonBeanRegistry 负责管理单例 bean,但它并不直接与用户交互。通常,用户会通过 ApplicationContext 接口或其实现类(如 ClassPathXmlApplicationContext、AnnotationConfigApplicationContext 等)来与 Spring 容器进行交互,而这些接口和类内部会使用 DefaultSingletonBeanRegistry 来管理单例 bean。

    源码

    public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {/** Maximum number of suppressed exceptions to preserve. */private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;/** Cache of singleton objects: bean name to bean instance. *///一级缓存 key:beanName value:beanInstanceprivate final Map singletonObjects = new ConcurrentHashMap(256);/** Cache of singleton factories: bean name to ObjectFactory. *///三级缓存 key:beanName value:ObjectFactory  三级缓存主要是解决存在动态代理的bean处理private final Map singletonFactory = this.singletonFactories.get(beanName);if (singletonFactory != null) {//调用getObject()方法返回beansingletonObject = singletonFactory.getObject();//这时bean是半成品 则放入二级缓存中this.earlySingletonObjects.put(beanName, singletonObject);//从三级缓存中移除this.singletonFactories.remove(beanName);}}}}}}return singletonObject;}/** * Return the (raw) singleton object registered under the given name, * creating and registering a new one if none registered yet. * @param beanName the name of the bean * @param singletonFactory the ObjectFactory to lazily create the singleton * with, if necessary * @return the registered singleton object */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) {//如果是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 + "'");}//标记当前 bean 被创建,如果有构造函数注入的循环依赖会报错beforeSingletonCreation(beanName);boolean newSingleton = false;boolean recordSuppressedExceptions = (this.suppressedExceptions == null);if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet();}try {//调用getObject() 方法实际上就是调用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.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;}}/** * 删除bean */protected void removeSingleton(String beanName) {synchronized (this.singletonObjects) {this.singletonObjects.remove(beanName);this.singletonFactories.remove(beanName);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.remove(beanName);}}/** * 当前bean是否正在创建中 */public boolean isSingletonCurrentlyInCreation(String beanName) {return this.singletonsCurrentlyInCreation.contains(beanName);}/** * 给BeanName 注册依赖 */public void registerDependentBean(String beanName, String dependentBeanName) {String canonicalName = canonicalName(beanName);synchronized (this.dependentBeanMap) {Set dependentBeans =this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet(8));if (!dependentBeans.add(dependentBeanName)) {return;}}synchronized (this.dependenciesForBeanMap) {Set dependenciesForBean =this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet(8));dependenciesForBean.add(canonicalName);}}/** * 是否包含这个依赖bean */protected boolean hasDependentBean(String beanName) {return this.dependentBeanMap.containsKey(beanName);}/** * 根据beanName 获取这个bean所依赖的bean */public String[] getDependentBeans(String beanName) {Set dependentBeans = this.dependentBeanMap.get(beanName);if (dependentBeans == null) {return new String[0];}synchronized (this.dependentBeanMap) {return StringUtils.toStringArray(dependentBeans);}}/** *清除所有缓存 */protected void clearSingletonCache() {synchronized (this.singletonObjects) {this.singletonObjects.clear();this.singletonFactories.clear();this.earlySingletonObjects.clear();this.registeredSingletons.clear();this.singletonsCurrentlyInDestruction = false;}}}

上一篇:香港云服务器怎么建站点?

下一篇:服务器ipv6怎么设置?