Springソース-キャッシュでの単一例beanの取得

3679 ワード

Spring 3.2ソースコードは以下の通りです.
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 != NULL_OBJECT ? singletonObject : null);
    }

説明:まずsingletonObjectsからインスタンスを取得し、取得できない場合はearlySingletonObjectsから取得し、取得できない場合はsingletonFactoriesからbeanName対応のobjectFactoryを取得し、getObjectを呼び出してbeanを作成します.earlySingletonObjectsに入れてsingletonFactoriesから取り除きます.
ここには多くのMapが含まれています
/** Cache of singleton objects: bean name --> bean instance */
    private final Map singletonObjects = new ConcurrentHashMap(64);

    /** Cache of singleton factories: bean name --> ObjectFactory */
    private final Map> singletonFactories = new HashMap>(16);

    /** Cache of early singleton objects: bean name --> bean instance */
    private final Map earlySingletonObjects = new HashMap(16);

    /** Set of registered singletons, containing the bean names in registration order */
    private final Set registeredSingletons = new LinkedHashSet(64);

1.singletonObjects:beanNameとbeanインスタンスの作成の関係を保存する2.singletonFactories:beanNameとbeanを作成する工場の関係を保存するために使用されます.earlySingletonObjects:beanNameとbeanインスタンスの関係を保存することでもあります.singletonObjectsとは異なり、単一のbeanがここに置かれた後、beanが作成中である場合、getBeanの方法で取得できます.その目的は、ループ参照を検出することです.4.registeredSingletons:現在登録されているすべてのbeanを保存します.