Bean是如何创建的 bean本质上就是对象,创建bean使用构造方法完成。 实例化Bean的几种方式 构造方法方式 1 2 3 4 5 6 7 8 public class BookDaoImpl implements BookDao { public BookDaoImpl () { System.out.println("book dao constructor is running ...." ); } public void save () { System.out.println("book dao save ..." ); } }
applicationContext.xml配置: 1 2 <bean id ="bookDao" class ="edu.heuet.dao.impl.BookDaoImpl" />
1 2 3 4 5 6 7 8 9 public class AppForInstanceBook { public static void main (String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext ("applicationContext.xml" ); BookDao bookDao = (BookDao) ctx.getBean("bookDao" ); bookDao.save(); } }
注意:无参构造方法如果不存在,将抛出异常BeanCreationException
静态工厂方式 OrderDao接口和OrderDaoImpl实现类: 1 2 3 4 5 6 7 8 public interface OrderDao { public void save () ; } public class OrderDaoImpl implements OrderDao { public void save () { System.out.println("order dao save ..." ); } }
1 2 3 4 5 6 7 public class OrderDaoFactory { public static OrderDao getOrderDao () { System.out.println("factory setup...." ); return new OrderDaoImpl (); } }
applicationContext.xml配置: 1 2 <bean id ="orderDao" class ="edu.heuet.factory.OrderDaoFactory" factory-method ="getOrderDao" />
1 2 3 4 5 6 7 8 9 public class AppForInstanceOrder { public static void main (String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext ("applicationContext.xml" ); OrderDao orderDao = (OrderDao) ctx.getBean("orderDao" ); orderDao.save(); } }
实例工厂方式 UserDao接口和UserDaoImpl实现类: 1 2 3 4 5 6 7 8 public interface UserDao { public void save () ; } public class UserDaoImpl implements UserDao { public void save () { System.out.println("user dao save ..." ); } }
1 2 3 4 5 6 public class UserDaoFactory { public UserDao getUserDao () { return new UserDaoImpl (); } }
1 2 3 4 <bean id ="userFactory" class ="edu.heuet.factory.UserDaoFactory" /> <bean id ="userDao" factory-method ="getUserDao" factory-bean ="userFactory" />
1 2 3 4 5 6 7 8 9 10 11 12 public class AppForInstanceUser { public static void main (String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext ("applicationContext.xml" ); UserDao userDao = (UserDao) ctx.getBean("userDao" ); userDao.save(); } }
实现FactoryBean<T>方式 定义UserDaoFactoryBean实现FactoryBean<UserDao> UserDaoFactoryBean中实例化什么类型的对象泛型就是该类型。
1 2 3 4 5 6 7 8 9 10 11 public class UserDaoFactoryBean implements FactoryBean <UserDao> { public UserDao getObject () throws Exception { return new UserDaoImpl (); } public Class<?> getObjectType() { return UserDao.class; } }
applicationContext.xml配置: 1 2 <bean id ="userDao" class ="edu.heuet.factory.UserDaoFactoryBean" />