bean的加载

 

bean的加载都是通过 getBean这个方法开始的。

public Object getBean(String name) throws BeansException {
        return doGetBean(name, null, null, false);
    }

调用doGetBean方法

1) 先去缓存中找  (解决依赖注入)

2) 加载依赖的实例

3) 创建实例

 

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

一 二 三 级缓存都存在 DefaultSingletonBeanRegistry这个类中

    /** Cache of singleton objects: bean name to bean instance. */
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);    // 一级

    /** Cache of singleton factories: bean name to ObjectFactory. */
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);     // 三级

    /** Cache of early singleton objects: bean name to bean instance. */
    private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);       // 二级

 

 

 

 

 

 

 

参考文档:

三级缓存、循环依赖:  https://blog.csdn.net/f641385712/article/details/92801300?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare

posted @ 2020-07-07 08:14  你眼里的星辰  阅读(96)  评论(0)    收藏  举报