Spring Bean的生命週期之我的理解(三)------BeanFactory和FactoryBean
阿新 • • 發佈:2018-12-29
前言
大家可能使用Spring框架已經很久了,但是對其中的一些概念可能會比較模糊,比如BeanFactory和FactoryBean,詐一看,兩個沒啥區別,仔細研究後發現,其實本質上是兩個不同的單元。
概念
BeanFactory
字面意思講就是Bean的工廠,是Spring重要的IOC容器,維護著整個Bean的生命週期。
FactoryBean
字面意思就是個工廠Bean,屬於Spring Bean的一種,是一種特殊的Bean。可以藉助工廠Bean得到某一個特殊Bean的例項。
原始碼
說到獲取某一個Bean的例項,不得不說的一個比較重要的類《AbstractBeanFactory》,所有的獲取Bean的方法都會由此類的doGetBean方法所接管。
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
// 沒細看這個方法,感覺沒大用
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// 從正在建立的單例型別Bean快取中檢視是否已經存在
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 從正在建立的原型型別Bean快取中檢視是否已經存在
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 檢視工廠中是否已經存在該Bean的定義
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
// 標記Bean的狀態為已經建立
markBeanAsCreated(beanName);
}
try {
// 如果有父Bean定義,則做一次合併操作
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 對合並後的Bean定義再做一次檢查
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 檢測Bean的依賴關係,優先初始化依賴的Bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// Create bean instance.
// 建立單例型別Bean的例項,也就是如果當前的Bean是單例型別的,執行此邏輯
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);
}
// 建立原型型別的Bean的例項
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 建立作用域型別的Bean的例項
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
誤區
我曾經誤認為BeanFactory會呼叫FactoryBean的實現來獲得Bean的例項,其實是不正確的,只有特殊的實現了FactoryBean介面的Bean的例項才會從FactoryBean的實現中獲取,其他的時候都是通過AbstractAutowireCapableBeanFactory的createBean方法獲取。
待續
下一節我將分析AbstractAutowireCapableBeanFactory原始碼的createBean方法。