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
FactoryBean是用来向容器中注入Bean的接口。而BeanFactory是从容器中取Bean的接口。