FactoryBean和BeanFactory都是spring的一個類工廠,BeanFactory只能生產一種類型的類,FactoryBean可以生產兩種類型的類,一種跟BeanFactory類似,生產的是當前對象,另一種是通過getObject()返回的對象。
FactoryBean要返回當前本身的對象時,需要在getBean()時,在獲取的對象前面加&,如:getBean("&daoFactoryBean")。當一個類依賴關系很復雜的時候,而我們有需要使用這個類對象時采用FactoryBean獲取。如我們mybatis中經常使用的sqlSessionFactory 對象,他就是通過 SqlSessionFactoryBean實現FactoryBean,通過getObject()方法獲取的。
FactoryBean通過getObject()獲取對象示例如下:
@Component("daoFactoryBean") public class DaoFactoryBean implements FactoryBean { public void testBean(){ System.out.println("testBean"); } @Override public Object getObject() throws Exception { return new TempDaoFactoryBean(); } public Class<?> getObjectType() { return TempDaoFactoryBean.class; } @Override public boolean isSingleton() { return true; } }
public class TempDaoFactoryBean { public void test(){ System.out.println("FactoryBean"); } }
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Appconfig.class); TempDaoFactoryBean temp = (TempDaoFactoryBean)ac.getBean("daoFactoryBean"); temp.test(); } } 運行結果:FactoryBean
FactoryBean獲取本身對象示例:
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Appconfig.class); DaoFactoryBean temp = (DaoFactoryBean)ac.getBean("&daoFactoryBean"); temp.testBean(); } }
運行結果:testBean