首先初始化容器
- 创建对象(内存分配)
- 执行构造方法
- 执行属性注入(set操作)
- 执行bean初始化方法
使用bean
1. 执行业务操作
2.关闭/销毁容器
3.执行bean销毁方法
case1:没有依赖注入的情况
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
<bean id="tableDao" class="com.itheima.dao.impl.TableDaoImpl" init-method="init" destroy-method="destory"/>
输出:
bookdao construct...
book dao init...
tabledao construct...
tabledao init...
tabledao destory...
book dao destory...
后创建的bean先销毁?–是的
<bean id="tableDao" class="com.itheima.dao.impl.TableDaoImpl" init-method="init" destroy-method="destory"/>
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
输出:
tabledao construct...
tabledao init...
bookdao construct...
book dao init...
book dao destory...
tabledao destory...
case2:bean存在依赖注入
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
public BookServiceImpl() {
System.out.println("constructing...");
}
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set .....");
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
public void destroy() throws Exception {
System.out.println("service destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("service init");
}
}
case2:实现 InitializingBean, DisposableBean 接口中的afterPropertiesSet() 和destroy()方法,同给bean配置init-method/destory-method等价。
public class TableDaoImpl implements TableDao, InitializingBean, DisposableBean {
public TableDaoImpl() {
System.out.println("tabledao construct...");
}
@Override
public void table() {
System.out.println("doing table...");
}
@Override
public void destroy() throws Exception {
System.out.println("tabledao destory...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("tabledao init...");
}
}
<bean id="tableDao" class="com.itheima.dao.impl.TableDaoImpl" />
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
输出:
tabledao construct...
tabledao init...
bookdao construct...
book dao init...
book dao destory...
tabledao destory...
case3:存在依赖注入的情况: