All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.osgl.inject.ScopedProvider Maven / Gradle / Ivy

There is a newer version: 1.13.2
Show newest version
package org.osgl.inject;

import org.osgl.inject.annotation.RequestScoped;
import org.osgl.inject.annotation.SessionScoped;

import javax.inject.Provider;
import javax.inject.Singleton;
import java.lang.annotation.Annotation;

/**
 * Decorate on a {@link javax.inject.Provider} with scope cache
 * checking function
 */
class ScopedProvider implements Provider {

    private Provider realProvider;
    private Class targetClass;
    private ScopeCache cache;

    private ScopedProvider(Class targetClass, ScopeCache cache, Provider realProvider) {
        this.targetClass = targetClass;
        this.realProvider = realProvider;
        this.cache = cache;
    }

    @Override
    public T get() {
        T bean = cache.get(targetClass);
        if (null == bean) {
            bean = realProvider.get();
        }
        cache.put(targetClass, bean);
        return bean;
    }

    static  Provider decorate(BeanSpec spec, Provider realProvider, Genie genie) {
        if (realProvider instanceof ScopedProvider) {
            return realProvider;
        }
        Class targetClass = spec.rawType();
        ScopeCache cache = resolve(spec.scope(), genie);

        return null == cache ? realProvider : new ScopedProvider(targetClass, cache, realProvider);
    }

    static ScopeCache resolve(Class annoClass, Genie genie) {
        ScopeCache cache = resolveBuiltIn(annoClass, genie);
        if (null != cache) {
            return cache;
        }
        Class alias = genie.scopeByAlias(annoClass);
        if (null != alias) {
            cache = resolveBuiltIn(alias, genie);
        }
        if (null == cache) {
            cache = genie.scopeCache(annoClass);
        }
        return cache;
    }

    private static ScopeCache resolveBuiltIn(Class annoClass, Genie genie) {
        if (Singleton.class == annoClass) {
            return genie.get(ScopeCache.SingletonScope.class);
        } else if (RequestScoped.class == annoClass) {
            return genie.get(ScopeCache.RequestScope.class);
        } else if (SessionScoped.class == annoClass) {
            return genie.get(ScopeCache.SessionScope.class);
        }
        return null;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy