该接口是一个简单的对象注册表,在启动和 Environment 后处理期间可用,直到准备好ApplicationContext为止。可以用于注册创建成本较高或需要在ApplicationContext可用之前共享的实例。注册表使用Class作为键,这意味着只能存储给定类型的单个实例。
该接口定义了以下几个方法。
// 向注册表注册特定类型。如果指定的类型已注册,但尚未作为单例获得,则将替换它。
<T> void register(Class<T> type, InstanceSupplier<T> instanceSupplier);
// 如果尚未注册特定类型,请向注册表注册该类型。
<T> void registerIfAbsent(Class<T> type, InstanceSupplier<T> instanceSupplier);
//如果给定类型存在注册,则返回true,否则返回false
<T> boolean isRegistered(Class<T> type);
// 返回给定类型的任何现有BootstrapRegistry.InstanceSupplier
<T> InstanceSupplier<T> getRegisteredInstanceSupplier(Class<T> type);
// 添加一个ApplicationListener,当BootstrapContext关闭且ApplicationContext已准备好时,将使用BootstrapContextClosedEvent调用它。
// 可用于添加一个监听器,该监听器可在BootstrapContext已关闭且ApplicationContext已完全准备好时执行操作。例如,一个实例可以选择将自己注册为一个普通的Springbean,以便应用程序可以使用它。
void addCloseListener(ApplicationListener listener);
//该函数式接口的功能是: 在需要时提供实际实例
@FunctionalInterface
interface InstanceSupplier {
// 工厂方法,用于在需要时创建实例。
T get(BootstrapContext context);
// 返回所提供实例的作用域,默认为单例
default Scope getScope() {
return Scope.SINGLETON;
}
// 返回一个新的 BootstrapRegistry.InstanceSupplier,其中包含一个更新的BootstrapRegistry.Scope
default InstanceSupplier<T> withScope(Scope scope) {
Assert.notNull(scope, "Scope must not be null");
InstanceSupplier<T> parent = this;
return new InstanceSupplier<T>() {
@Override
public T get(BootstrapContext context) {
return parent.get(context);
}
@Override
public Scope getScope() {
return scope;
}
};
}
//可用于为给定实例创建 BootstrapRegistry.InstanceSupplier的工厂方法
static <T> InstanceSupplier<T> of(T instance) {
return (registry) -> instance;
}
// 可用于从Supplier创建BootstrapRegistry.InstanceSupplier的工厂方法
static <T> InstanceSupplier<T> from(Supplier<T> supplier) {
return (registry) -> (supplier != null) ? supplier.get() : null;
}
//实例作用域枚举
enum Scope {
// 单例实例。BootstrapRegistry.InstanceSupplier只会被调用一次,每次都会返回相同的实例。
SINGLETON,
// 原型实例。只要需要实例就会调用BootstrapRegistry.InstanceSupplier
PROTOTYPE
}
}
至此,BootstrapRegistry接口分析完毕。