Spring: Bean创建过程中的ObjectFactory

AbstractBeanFactory中doGetBean方法里有一段拿到RootBeanDefinition后,实例化该bean的方法。

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

ObjectFactory是一个普通的对象工厂接口。在AbstractBeanFacotrydoGetBean部分的源码中,可以看到springObjectFactory的应用之一就是,
将创建对象的步骤封装到ObjectFactory中 交给自定义的Scope来选择是否需要创建对象来灵活的实现Scope

ObjectFactory

定义一个工厂,它可以在调用时返回一个对象实例(可能是共享的或独立的)。
这个接口通常用于封装泛型工厂,在每次调用时返回某个目标对象的新实例(原型)。
这个接口类似于FactoryBean,但是后者的实现通常被定义为BeanFactory中的SPI实例,而这个类的实现通常被定义为作为API(通过注入)提供给其他bean。
因此,getObject()方法有不同的异常处理行为

详情: https://blog.csdn.net/u012291108/article/details/51886269