BeanFactory(Bean工厂)
Spring中进行Bean收集管理的容器,用于Bean的管理以及缓存
属于IOC容器接口,定义IOC容器管理Bean的规范接口.用于管理Bean(查找Bean以及获取Bean部分元信息)
BeanFactory中有三级缓存容器用于在Bean的不同创建时期进行Bean缓存操作.分别为
singletonObjects: 用于存放已经完成Bean创建生命周期的完整Bean
earlySingletonObjects: 已经完成Bean创建初始化的Bean
singletonFactories: 存放可以生成对应Bean的FactoryBean.通过FactoryBean.getObject可以获取到对应Bean实例
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
FactoryBean(Bean创建工厂)
本身也属于BeanFactory容器中的一个Bean,用于当指定的Bean不存在时创建对应的对象Bean.是一个功能Bean,用于创建目标对象
本身是一个接口,提供了Bean创建的拓展方式.我们实现该接口并实现getObject方法用于自定义指定类的创建逻辑,例如返回该Bean的代理对象到容器中.
可参考这个代码了解功能