研究bean的生命周期(待完善)

首先初始化容器

  1. 创建对象(内存分配)
  2. 执行构造方法
  3. 执行属性注入(set操作)
  4. 执行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:存在依赖注入的情况:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值