Spring-IOC bean 創建過程中的 ObjectFactory


AbstractBeanFactory中doGetBean方法里有一段拿到RootBeanDefinition后,實例化該bean的方法

// 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM