企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
spring三级缓存: * singletonObjects 一级缓存,用于保存实例化、注入、初始化完成的bean实例 * earlySingletonObjects 二级缓存,用于保存**实例化(但未初始化)**完成的bean实例 * singletonFactories 三级缓存,用于保存bean创建工厂(ObjectFactory),以便于后面扩展有机会创建代理对象 ``` /** Cache of singleton objects: bean name --> bean instance */ private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256); /** Cache of singleton factories: bean name --> ObjectFactory */ private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16); /** Cache of early singleton objects: bean name --> bean instance */ private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16); ``` 获取单例Bean的源码如下: 1. 先从一级缓存singletonObjects中去获取。(如果获取到就直接return) 2. 如果获取不到或者对象正在创建中(isSingletonCurrentlyInCreation()),那就再从二级缓存earlySingletonObjects中获取。(如果获取到就直接return) 3. 如果还是获取不到,且允许singletonFactories(allowEarlyReference=true)通过getObject()获取。就从三级缓存singletonFactory.getObject()获取。(如果获取到了就从singletonFactories中移除,并且放进earlySingletonObjects) > 加入`singletonFactories`三级缓存的前提是执行了构造器,所以构造器的循环依赖没法解决 ``` public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { ... @Override @Nullable public Object getSingleton(String beanName) { return getSingleton(beanName, true); } @Nullable 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); if (singletonObject == null && allowEarlyReference) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return singletonObject; } ... public boolean isSingletonCurrentlyInCreation(String beanName) { return this.singletonsCurrentlyInCreation.contains(beanName); } protected boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName); } ... } ``` ``` // 它可以将创建对象的步骤封装到ObjectFactory中 交给自定义的Scope来选择是否需要创建对象来灵活的实现scope。 具体参见Scope接口 @FunctionalInterface public interface ObjectFactory<T> { T getObject() throws BeansException; } ``` 经过ObjectFactory.getObject()后,此时放进了二级缓存**`earlySingletonObjects`**内。这个时候对象已经实例化了,**`虽然还不完美`**,但是对象的引用已经可以被其它引用了