bean实例化-静态工厂
bean实例化-静态工厂
-
静态工厂
//OrderDaoFactory.java 工厂类 public class OrderDaoFactory { public static OrderDao getOrderDao(){ System.out.println("factory setup..."); return new OrderDaoImpl(); } } //OrderDao.java 接口类 public interface OrderDao { void save(); } //OrderDaoImpl.java 接口实现类 public class OrderDaoImpl implements OrderDao { @Override public void save() { System.out.println("order dao save..."); } } //AppForInstanceOrder.java 测试类 public class AppForInstanceOrder { public static void main(String[] args) { //通过静态工厂创建对象 /*OrderDao orderDao = OrderDaoFactory.getOrderDao(); orderDao.save();*/ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); OrderDao orderDao = (OrderDao) ctx.getBean("orderDao"); orderDao.save(); } }
-
配置
<!--方式二:使用静态工厂实例化bean--> <bean id="orderDao" class="com.charley.factory.OrderDaoFactory" factory-method="getOrderDao"/>