Skip to content

Instantly share code, notes, and snippets.

@kissarat
Created January 31, 2022 18:42
Show Gist options
  • Save kissarat/b2dfdf258fce6af933bc838207d5c2e5 to your computer and use it in GitHub Desktop.
Save kissarat/b2dfdf258fce6af933bc838207d5c2e5 to your computer and use it in GitHub Desktop.
package profitworld;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public abstract class ContextManager<T> implements ApplicationContextAware {
private final Map<String, T> beans;
private ApplicationContext context;
private final boolean isSingletons;
private final Class<T> itemClass;
public ContextManager(Class<T> itemClass, boolean isSingletons, Map<String, T> beans, ApplicationContext context) {
this.itemClass = itemClass;
this.isSingletons = isSingletons;
this.beans = null == beans
? new HashMap<String, T>()
: beans;
this.context = context;
}
public boolean hasContext() {
return null != context;
}
public T get(String name) {
T bean = null;
if (hasContext() && context.containsBean(name)) {
bean = (T) context.getBean(name);
}
if (null == bean) {
bean = beans.get(name);
}
if (null == bean) {
throw new Error("Bean " + name + " not found");
}
return bean;
}
public boolean contains(String name) {
if (beans.containsKey(name)) {
return true;
}
return hasContext() && context.containsBean(name);
}
public void put(String name, T bean) {
if (beans.containsKey(name)) {
throw new Error("Bean " + name + " already exists");
}
beans.put(name, bean);
}
public T remove(String name) {
return beans.remove(name);
}
// public Collection<T> names() {
// Collection<T> items = beans.values();
// if (hasContext()) {
// context.getBeanNamesForType(itemClass, this.isSingletons, false);
// }
// return items;
// }
// public Collection<T> values() {
// Collection<T> items = beans.values();
// if (hasContext()) {
// context.getBeansOfType(itemClass, this.isSingletons, false);
// }
// return items;
// }
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment