FactoryBean也能夠算是容器擴展的一部分。當須要對一個bean進行復雜的初始化,能夠考慮用FactoryBean。
FactoryBean接口提供了三個方法:app
若是想要對象自己,就在getbean的時候,前面加個&。
MyFactoryBeanide
public class MyFactoryBean implements FactoryBean { @Override public MyBean getObject() throws Exception { return new MyBean(); } @Override public Class<?> getObjectType() { return MyBean.class; } @Override public boolean isSingleton() { return false; } }
MyConfig測試
@Configuration public class MyConfig { @Bean public MyFactoryBean myFactoryBean() { return new MyFactoryBean(); } }
測試代碼spa
@Test public void test(){ ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); Object myBean = app.getBean("myFactoryBean"); Object myBean2 = app.getBean("myFactoryBean"); Object myFactoryBean = app.getBean("&myFactoryBean"); Object myFactoryBean2 = app.getBean("&myFactoryBean"); System.out.println(myBean); System.out.println(myBean2); System.out.println(myFactoryBean); System.out.println(myFactoryBean2); }
運行結果以下:
若是直接調用app.getBean("myFactoryBean"),返回的類型是getObjectType這個方法返回的類型,返回的對象是getObject返回的對象,與實現的接口有關。
若是直接調用app.getBean("&myFactoryBean"),那返回的類型就是MyFactoryBean。
由於isSingleton返回的是false,因此app.getBean("myFactoryBean")獲得的兩次結果是不同的,app.getBean("&myFactoryBean")獲得的結果是同樣的,他們都返回myFactoryBeanbean自己。code