- bean是如何创建的实例化bean的三种方式
- 构造方法
- 静态工厂(了解)
- 实例工厂与FactoryBean
- 实例工厂
- FactoryBean
bean是如何创建的实例化bean的三种方式
构造方法
bean本质上就是对象,创建bean使用构造方法完成
提供可访问的构造方法
public class BookDaoimpl implements BookDao {
private BookDaoimpl() {
System.out.println("book dao constructor is running...");
}
public void save(){
System.out.println("user dao save...");
}
}
配置
<bean id="bookDao" class="com.dao.impl.BookDaoimpl"/>
无参构造方法如果不存在,将抛出异常BeanCreationException
例
静态工厂(了解)
静态工厂
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
return new OrderDaoimpl();
}
}
配置注意配置的工厂名及方法名
<bean id="orderDao" class="com.dao.factory.OrderDaoFactory" factory-method="getOrderDao"/>
实例工厂与FactoryBean
实例工厂
public class UserDaoFactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
配置(先配置工厂的bean并使用factory-bean指定工厂bean)配合使用实际无意义方法名不固定每次需要配置
<bean id="userFactory" class="com.dao.factory.UserDaoFactory"/>
<bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"/>
FactoryBean
FactoryBean(务必掌握)
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
@Override
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
}
配置
<bean id="userDao" class="com.dao.factory.UserDaoFactoryBean"/>
FactoryBean默认为单例如果要改非单例需要加上isSingleton返回值true为单例false为非单例
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
//代替原始实例工厂中创建对象的方法
@Override
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
@Override
public boolean isSingleton() {
return false;
}
}