ApplicationContext.xml文档:
<!-- bean实例化三种方式: 1. 用构造器来实例化 (掌握) 2. 使用静态工厂方法实例化 (理解) 3. 使用实例工厂方法实例化 (理解) --> <!-- 1、用构造器来实例化:使用class的默认无参构造函数实例化 IUserDao userDao = new UserDaoImpl(); --> <bean id ="userDao" class="spring.UserDaoImpl"></bean> <!-- 使用静态工厂方法实例化 IUserDao userDao2= DaoStaticFactory.createUserDao(); --> <bean id="userDao2" class="spring.factory.DaoStaticFactory" factory-method="createUserDao"></bean> <!-- 使用实例化工厂方法实例化 DaoNotStaticFactory factory = new DaoNotStaticFactory(); IUserDao userDao3= factory.createUserDao(); --> <bean id="factory" class="spring.factory.DaoNotStaticFactory" ></bean> <bean id="userDao3" factory-bean="factory" factory-method="createUserDao"></bean>实例化工厂:DaoNotStaticFactory
package spring.factory; import spring.IUserDao; import spring.UserDaoImpl; /* * 实例工厂 */ public class DaoNotStaticFactory { //DaoNotStaticFactory factory = new DaoNotStaticFactory(); //IUserDao userDao3= factory.createUserDao(); public IUserDao createUserDao() { return new UserDaoImpl(); } }静态实例化工厂:DaoStaticFactory
package spring.factory; import spring.IUserDao; import spring.UserDaoImpl; /* * 静态工厂:方法使用static修饰 */ public class DaoStaticFactory { //IUserDao userDao2= DaoStaticFactory.createUserDao(); public static IUserDao createUserDao() { return new UserDaoImpl(); } }test:
package spring.factory; import org.springframework.context.support.ClassPathXmlApplicationContext; import spring.IUserDao; public class test { public static void main(String[] args) { //加载并解析ApplicationContext.xml ClassPathXmlApplicationContext factory= new ClassPathXmlApplicationContext("applicationContext.xml"); //获取工厂中的IUseDao对象 IUserDao userDao= (IUserDao)factory.getBean("userDao"); IUserDao userDao2= (IUserDao)factory.getBean("userDao2"); IUserDao userDao3= (IUserDao)factory.getBean("userDao3"); //掉用方法 userDao.selectUser(); userDao2.selectUser(); userDao3.selectUser(); //销毁对象 factory.close(); } }