Spring-实例化bean的3种方式

推荐先阅读Spring全家桶

1.构造方法

提供可访问的构造方法

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 id="bookDao" class="com.zx.dao.impl.BookDaoImpl"/>

注意:无参构造方法如果不存在,将抛出异常BeanCreationException

2.静态工厂(了解)

//静态工厂创建对象
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
return new OrderDaoImpl();
}
}

配置

<bean id="orderDao" class="com.zx.factory.OrderDaoFactory" factory-method="getOrderDao"/>

3.实例工厂

public class UserDaoFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}

配置

<bean id = "userDaoFactory" class = "com.zx.factory.UserDaoFactory" />
<bean id = "userDao" factory-method = "getUserDao" factory-bean = "userDaoFactory" />

注意:第一个bean配合使用的,实际无意义。工厂方法名不固定,每次需要配置。

实例工厂改良(实现FactoryBean)

public class UserDaoFactoryBean implements FactoryBean<UserDao> {
//代替原始实例工厂中创建对象的方法
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
//返回所创建类的Class对象
public Class<?> getObjectType() {
return UserDao.class;
}
// 默认为true,单例,可以不重写
default boolean isSingleton() {
return true;
}
}

配置

<bean id="userDao" class="com.zx.factory.UserDaoFactoryBean"/>