美文网首页
4.1.1Spring源码解析——getBean方法细节之get

4.1.1Spring源码解析——getBean方法细节之get

作者: szhlcy | 来源:发表于2018-10-19 14:33 被阅读0次

1.getSingleton方法的第一个方法是获取bean的步骤中获取单例bean的关键方法,进行相关分析关于getBean方法的整体解析可以看这里getBean方法解析

    public Object getSingleton(String beanName) {
        return getSingleton(beanName, true);
    }
        
    //具体实现
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        //在已经注册了的单例map集合(singletonObjects)中获取特定beanName的bean
        Object singletonObject = this.singletonObjects.get(beanName);
        //检查这个bean是不是null,并且这个bean不在正在创建中的bean的map缓存(singletonsCurrentlyInCreation)中
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                //从已经缓存了的单利对象集合中获取beanName对应的Bean
                singletonObject = this.earlySingletonObjects.get(beanName);
                    //如果不存在,并且允许早期引用当前创建的对象
                if (singletonObject == null && allowEarlyReference) {
                    //根据beanName获取在可以在调用时返回单例Object实例)的工厂。
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                        //如果返回的工厂不为空就把对应的beanName放到earlySingletonObjects中,并移除singletonFactories中的值
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        //如果获取到的对象是空,就返回null
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }

相关文章

网友评论

      本文标题:4.1.1Spring源码解析——getBean方法细节之get

      本文链接:https://www.haomeiwen.com/subject/laiyzftx.html