【Spring】04-3:bean的初始化、摧毁方法

101 阅读1分钟

bean生命周期:

  1. 初始化 容器
    • 创建对象(分配内存)
    • 执行构造方法
    • 执行属性注入(set操作)
    • 执行bean初始化方法
  2. 使用bean
    • 执行业务操作
  3. 关闭/销毁 容器
    • 执行bean销毁方法

01:配置文件中,属性init/destroy-method=""

<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ...");
    }

    //表示bean初始化对应的操作
    public void init() {
        System.out.println("init...");
    }

    //表示bean销毁前对应的操作
    public void destory() {
        System.out.println("destory...");
    }
}
public static void main( String[] args ) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

    BookDao bookDao = (BookDao) ctx.getBean("bookDao");
    bookDao.save();
    //注册关闭钩子函数,在虚拟机退出之前回调此函数,关闭容器(该语句可以在任何位置)
    //ctx.registerShutdownHook();

    //关闭容器(暴力)(只能在最后关闭)
    ctx.close();
}

02:类继承InitializingBean, DisposableBean,重写destroy()afterPropertiesSet()

public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
    public void destroy() throws Exception {
        System.out.println("service destroy");
    }
    // after_Properties_Set:该函数的执行在setBookDao(DI)之后
    public void afterPropertiesSet() throws Exception {
        System.out.println("service init");
    }
    
    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();
    }
}