交流
商城
MCN
登入
注册
首页
提问
分享
讨论
建议
公告
动态
发表新帖
发表新帖
spring核心第3 章:SingletonBeanRegistry
分享
未结
0
840
李延
LV6
2021-05-13
悬赏:20积分
# 功能说明 用于保存所以已经初始化完成的单例对象。我们使用的所有spring单例bean对象都会保存在此处。 # 主要子类 接口的主要实现是DefaultSingletonBeanRegistry # 继承关系  ## SingletonBeanRegistry 单例对象注册表接口 定义了获取单例对象,注册单例对象、获取单例对象名称、数量等接口 ## DefaultSingletonBeanRegistry 主要方法 ### DefaultSingletonBeanRegistry#registerSingleton(String, Object) 添加 单例对象 ```java @Override 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); } } protected void addSingleton(String beanName, Object singletonObject) { synchronized (this.singletonObjects) { this.singletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } } ``` 我们可以看到 当添加单例对象时,最终会被保存在singletonObjects对象中,并且将名称保存在registeredSingletons中。但额外从singletonFactories、earlySingletonObjects中删除了对象,我们这里需要说明一下这3个类的具体作用。 spring的单例例对象用3个map来保存分别入下: {@linkplain DefaultSingletonBeanRegistry#singletonObjects} {@linkplain DefaultSingletonBeanRegistry#singletonFactories} {@linkplain DefaultSingletonBeanRegistry#earlySingletonObjects} 1、当一个对象刚被创建时,此时只是new出了这个对象,但还没有执行init方法与进行属性的注入。此时对于spring来说还不是一个完整的bean。而这个时候将会被封装为ObjectFactory 被保存在singletonFactories中。 2、之后spring将继续初始化这个对象。如果这个对象没有依赖其他bean则将直接创建完成。而此时将会调用上面的registerSingleton方法,将bean对象保存在singletonObjects。 3、如果这个bean依赖了其他对象,则会优先去创建依赖的对象,在创建依赖对象时存在循环依赖时,此时未创建完成的bean将会被从singletonFactories中取出。通过ObjectFactory 的get方法获取到真实对象。并零时保存在earlySingletonObjects中。当所有的创建完成后,依然调用registerSingleton将对象保存在singletonObjects中。
回帖
消灭零回复
提交回复
热议榜
java 相关知识分享
8
好的程序员与不好的程序员
6
写给工程师的十条精进原则
5
spring boot以jar包运行配置的logback日志文件没生成
5
一步一步分析SpringBoot启动源码(一)
5
MockMvc测试
5
【吐槽向】是不是有个吐槽的板块比较好玩
4
logstash jdbc同步mysql多表数据到elasticsearch
3
IntelliJ IDEA 优质License Server
3
.gitignore忽略规则
3
SpringBoot启动源码分析
3
一步一步分析SpringBoot启动源码(三)
3
2
一步一步分析SpringBoot启动源码(二)
2
积分不够将无法发表新帖
2
官方产品
Meta-Boot - 基于MCN
MCN - 快速构建SpringBoot应用
微信扫码关注公众号