Spring框架创建Java bean有三种方法
- 无参构造方法
- 静态工厂
- 实例工厂
Spring里面的FactoryBean是对实例工厂的优化和增强。
本文展示Spring框架的FactoryBean接口的使用方法,采用xml文件配置的方式。
package com.oxygen.factory; import com.oxygen.dao.OrderDao; import com.oxygen.dao.impl.OrderDaoImpl; import org.springframework.beans.factory.FactoryBean; public class OrderDaoFactoryBean implements FactoryBean<OrderDao> { @Override public OrderDao getObject() throws Exception { return new OrderDaoImpl() ; } @Override public Class<?> getObjectType() { return OrderDao.class; } //返回值true表示使用单例模式 //返回值false表示使用多例模式 @Override public boolean isSingleton() { return true; } }
Spring applicatin context的xml配置文件
<bean id="orderDao" class="com.oxygen.factory.OrderDaoFactoryBean"/>
测试:
package com.oxygen; import com.oxygen.dao.OrderDao; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App2 { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); OrderDao orderDao = context.getBean("orderDao", OrderDao.class); orderDao.save(); } }
标签:oxygen,OrderDao,Spring,FactoryBean,import,public From: https://www.cnblogs.com/majestyking/p/16796543.html