Spring原始碼窺探之:Spring IOC之FactoryBean
阿新 • • 發佈:2018-11-09
1. 定義Fish實體類
/** * @author 70KG * @Title: Fish * @Description: * @date 2018/7/22下午5:00 * @From www.nmyswls.com */ @Data public class Fish { private String name; private int age; public Fish(){} public Fish(String name, int age) { this.name = name;this.age = age; } }
2. 實現FactoryBean來注入實體類
/** * @author 70KG * @Title: FactoryBeanRegist * @Description: * @date 2018/7/22下午8:06 * @From www.nmyswls.com */ public class FactoryBeanRegist implements FactoryBean<Fish> { @Override public Fish getObject() throws Exception {return new Fish(); } @Override public Class<?> getObjectType() { return Fish.class; } @Override public boolean isSingleton() { return true; } }
3. 編寫配置類
/** * @author 70KG * @Title: FactoryBeanConfig * @Description: * @date 2018/7/22下午8:21 * @From www.nmyswls.com*/ @Configuration public class FactoryBeanConfig { @Bean public FactoryBeanRegist getBean() { return new FactoryBeanRegist(); } }
4. 測試
/** * @author 70KG * @Title: FactoryBean的測試類 * @Description: * @date 2018/7/22下午8:22 * @From www.nmyswls.com */ public class Test01 { @Test public void test() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(FactoryBeanConfig.class); // 不加"&"獲取到的是FactoryBean中的例項 Object getBean1 = ac.getBean("getBean"); // 加"&"獲取到的是實現了FactoryBean介面的FactoryBeanRegist本身 Object getBean2 = ac.getBean("&getBean"); System.out.println(getBean1.getClass()); System.out.println(getBean2.getClass()); } }
5. 測試結果
class com.nmys.story.springCore.springioc.importBean.Fish class com.nmys.story.springCore.springioc.factoryBean.FactoryBeanRegist