实例工厂:必须现有工厂的实例对象,通过实例对象创建对象。所有的方法都是非静态的(这一点和静态工厂有区别)
(直接看代码)
工厂(和静态工厂的区别就是非静态 其他都一样)
package c_inject.c_factory; /* * 实例工厂 */ public class MyBeanFactory { public UserService createService(){ return new UserserviceImpl(); } }
配置(配置和静态的有点区别 仔细看看吧 )
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 创建工厂实例 --> <bean id="MyBeanFactoryId" class="c_inject.c_factory.MyBeanFactory"> <!-- 获取userService factory-bean :确定工厂实例 factory-method : 确定工厂中的方法 --> <bean id="userServiceId" factory-bean="MyBeanFactoryId" factory-method="createService"></bean> </beans>
测试类 (静态自定义和实例自定义的区别大一点 当用spring的时候完全一样)
package c_inject.c_factory; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import a.ioc.Uservice; public class TestStaticFactory { @Test /* * 自定义实例工厂 */ public void demo01(){ //自定义实例工厂 //1.创建工厂 MyBeanFactory factory=new MyBeanFactory(); //通过工厂获取对象 UserService uservice= factory.createService(); uservice.addUser(); }; @Test /* * spring 的工厂 */ public void demo02(){ ApplicationContext application =new ClassPathXmlApplicationContext("c_inject/c_factory/beans.xml"); UserService userService = (UserService) application.getBean("userServiceId"); userService.addUser(); }; }