DefaultSingletonBeanRegistry深入理解

2019-02-20  本文已影响0人  小幽运

DefaultSingletonBeanRegistry继承了SimpleAliasRegistry并实现SingletonBeanRegistry,使得它既有管理SingletonBean的功能,又提供了别名的功能,它是一个通用的存储共享bean实例的地方。在注册一个SingletonBean的时候,用到了四个存储器

1:singletonObjects:用来存放注册的SingletonBean,具体的实现类是ConcurrentHashMap。

2:singletonFactories:存储制造 singleton 的工厂。

3:earlySingletonObjects:是singletonFactory 制造出来的 singleton 的缓存。

4:registeredSingletons:按顺序存放已经注册的SingletonBean的名称。

getSingleton的时候,spring的默认实现是,先从singletonObjects寻找,如果找不到,再从earlySingletonObjects寻找,仍然找不到,那就从singletonFactories寻找对应的制造singleton的工厂,然后调用工厂的getObject方法,造出对应的SingletonBean,并放入earlySingletonObjects中

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

}

上一篇 下一篇

猜你喜欢

热点阅读