Bean实例化
一. 构造方法进行实例化
bookDaoImpl
package dang.dao.impl;
import dang.dao.BookDao;
public class BookDaoImpl implements BookDao {
public BookDaoImpl() {
System.out.println("book dao constructor is running ....");
}
public void save() {
System.out.println("book dao save ...");
}
}
配置
<!--方式一:构造方法实例化bean-->
<bean id="bookDao" class="dang.dao.impl.BookDaoImpl"/>
二. 静态工厂实例化Bean(了解)
AppForInstanceOrder
package dang;
import dang.dao.OrderDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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();
}
}
ordeDaoFactory
package dang.factory;
import dang.dao.OrderDao;
import dang.dao.impl.OrderDaoImpl;
//静态工厂创建对象
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
System.out.println("factory setup....");
return new OrderDaoImpl();
}
}
配置
<bean id="orderDao" class="dang.factory.OrderDaoFactory" factory-method="getOrderDao"/>
三. 使用实例工厂实例化Bean
AppForInstanceUser
package dang;
import dang.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppForInstanceUser {
public static void main(String[] args) {
// //创建实例工厂对象
// UserDaoFactory userDaoFactory = new UserDaoFactory();
// //通过实例工厂对象创建对象
// UserDao userDao = userDaoFactory.getUserDao();
// userDao.save();
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao=(UserDao)ctx.getBean("userDao");
userDao.save();
}
}
UserDaoFactory
package dang.factory;
import dang.dao.UserDao;
import dang.dao.impl.UserDaoImpl;
//实例工厂创建对象
public class UserDaoFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
配置
<bean id="userFactory" class="dang.factory.UserDaoFactory"/>
<bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"/>
四. FactoryBean
UserDaoFactoryBean
package dang.factory;
import dang.dao.UserDao;
import dang.dao.impl.UserDaoImpl;
import org.springframework.beans.factory.FactoryBean;
//FactoryBean创建对象
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
//代替原始实例工厂中创建对象的方法
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
public Class<?> getObjectType() {
return UserDao.class;
}
}
<details>
<summary>配置</summary>
</details>
配置
<bean id="userDao" class="dang.factory.UserDaoFactoryBean"/>