package org.springframework.beans.factory; /** * Interface to be implemented by objects used within a {@link BeanFactory} * which are themselves factories. If a bean implements this interface, * it is used as a factory for an object to expose, not directly as a bean * instance that will be exposed itself. */ public interface FactoryBean<T> { /** * Return an instance (possibly shared or independent) of the object * managed by this factory. */ T getObject() throws Exception; /** * Return the type of object that this FactoryBean creates, * or {@code null} if not known in advance. */ Class<?> getObjectType(); /** * Is the object managed by this factory a singleton? That is, * will {@link #getObject()} always return the same object * (a reference that can be cached)? * 單例對象會放在Spring單例緩存池中 */ boolean isSingleton(); }
工廠方法配置bean如下:
<bean id="book" class="com.xxx.model.BookFactory"/>
BookFactory實現了FactoryBean,則當使用getBean("book")時,返回FactoryBean#getObject()方法返回的對象,即FactoryBean#getObject()代理了getBean()方法:
Book book = ctx.getBean("book");
如果要獲取BookFactoryBean對象,則需要使用前綴“&”,使用如下:
BookFactory bookFactory = ctx.getBean("&book");單例Bean(singleton)獲取步驟: singletonObjects<BeanName, BeanInstance>.get(beanName):Map單例緩存獲取。synchronized(this.singletonObjects),全局變量同步。 ↓↓ ↓↓==Null ↓↓ earlySingletonObjects<BeanName, BeanInstance> .get(beanName):處理循環引用依賴檢測。 ↓↓ ↓↓==Null ↓↓ singletonFactories<BeanName, BeanFactory> .get(beanName):調用相應單例創建工廠getObject()返回Bean對象。 ↓↓ -->earlySingletonObjects.put(beanName, singletonObject)存儲獲取的Bean實例。 --> singletonFactories.remove(beanName)移除beanName對應單例工廠。 Bean創建: Bean初始化:Aware方法,Post處理,Init處理。