
org.rx.core.IOC Maven / Gradle / Ivy
package org.rx.core;
import lombok.NonNull;
import lombok.SneakyThrows;
import org.rx.bean.WeakIdentityMap;
import org.rx.exception.InvalidException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static org.rx.core.Constants.NON_UNCHECKED;
@SuppressWarnings(NON_UNCHECKED)
public final class IOC {
static final Map, Object> container = new ConcurrentHashMap<>(8);
static final Map WEAK_MAP = Collections.synchronizedMap(new WeakHashMap<>());
//不要放值类型
static final Map WEAK_IDENTITY_MAP = new WeakIdentityMap<>();
public static boolean isInit(Class type) {
return container.containsKey(type);
}
public static T get(Class type, Class extends T> defType) {
T bean = innerGet(type);
if (bean == null) {
return get(defType);
}
return bean;
}
public static T get(Class type) {
T bean = innerGet(type);
if (bean == null) {
throw new InvalidException("Bean {} not registered", type.getName());
}
return bean;
}
@SneakyThrows
static synchronized T innerGet(Class type) {
T bean = (T) container.get(type);
if (bean == null) {
Class.forName(type.getName());
bean = (T) container.get(type);
}
return bean;
}
public static void register(@NonNull Class type, @NonNull T bean) {
List> types = new ArrayList<>();
types.add(type);
Class> superclass = type.getSuperclass();
if (superclass != null) {
types.add(superclass);
}
for (Class> i : type.getInterfaces()) {
types.add(i);
}
for (Class> t : types) {
container.putIfAbsent(t, bean);
}
container.put(type, bean);
}
public static void unregister(Class type) {
container.remove(type);
}
public static Map weakMap(boolean identity) {
return identity ? WEAK_IDENTITY_MAP : WEAK_MAP;
}
static Map weakMap(Object ref, boolean identity) {
return (Map) (identity ? WEAK_IDENTITY_MAP : WEAK_MAP).computeIfAbsent(ref, k -> new ConcurrentHashMap<>(4));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy