org.osgl.inject.ScopedProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of genie Show documentation
Show all versions of genie Show documentation
A JSR330 style dependency injection solution
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 extends Annotation> annoClass, Genie genie) {
ScopeCache cache = resolveBuiltIn(annoClass, genie);
if (null != cache) {
return cache;
}
Class extends Annotation> 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 extends Annotation> 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