在Spring Boot中除了ApplicationContextFactory生成的上下文以外还有一个特殊的上下文,它是引导上下文,引导上下文接口是BootstrapContext,引导上下文的默认实现是DefaultBootstrapContext,本节将对引导上下文做出分析。接下来对DefaultBootstrapContext成员变量进行说明,详细内容见表3-4。
表3-4 DefaultBootstrapContext成员变量
在上述成员变量中引出了实例提供商接口,关于该接口的定义代码如下:
在InstanceSupplier中有两个核心方法:
(1)获取实例,对应方法get;
(2)获取作用域,对应方法是getScope。
上述提到的作用域有两个,一个是单例(SINGLETON),另一个是原型(PROTOTYPE)。下面开始对接口的实现进行说明,在BootstrapRegistry中的注册方法:
在上述代码中提供了InstanceSupplier相关的注册方法,其核心实现流程是判断是否允许替换或者容器中不存在,如果判断通过会将其放入容器中。
了解注册后下面来对获取实例进行分析,具体分析目标是getOrElseSupply方法,核心处理代码如下:
public <T> T getOrElseSupply(Class<T> type, Supplier<T> other) { synchronized (this.instanceSuppliers) { InstanceSupplier<?> instanceSupplier = this.instanceSuppliers.get(type); return (instanceSupplier != null) ? getInstance(type, instanceSupplier) : other.get(); } } private <T> T getInstance(Class<T> type, InstanceSupplier<?> instanceSupplier) { T instance = (T) this.instances.get(type); if (instance == null) { instance = (T) instanceSupplier.get(this); if (instanceSupplier.getScope() == Scope.SINGLETON) { this.instances.put(type, instance); } } return instance; }
在获取实例时需要依赖成员变量instanceSuppliers,先从实例提供商容器中获取实例提供商对象,再通过实例提供商的get方法获取数据,如果获取成功会将其置入实例容器中。