国王陛下万万岁

导航

 

一个Bean的生命周期:

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

本文以xml配置的方式来记录Spring的初始化和销毁bean的方法.

Java Bean:

package com.oxygen.dao.impl;

import com.oxygen.dao.BookDao;

public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("Book Dao Save...");
    }
    public void init(){
        System.out.println("BookDaoImpl init...");
    }

    public void destroy(){
        System.out.println("BookDaoImpl destroy...");
    }
}

注意BookDaoImpl这个java类中的init()和destroy()方法,这两个方法是自己写的.

 

xml配置:告诉spring容器,谁是初始化方法,谁是销毁bean的方法

<bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl" init-method="init" destroy-method="destroy"/>

 

测试类:

package com.oxygen;

import com.oxygen.dao.BookDao;
import com.oxygen.dao.OrderDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App2 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        BookDao bookDao = (BookDao) context.getBean("bookDao");
        bookDao.save();
        context.close();
    }
}

注意:

上面的测试类用的是ClassPathXmlApplicationContext这个对象,而不是ApplicationContext。

在xml文件配置之后,初始化方法init()就会自动运行.

在xml文件配置之后,销毁bean的方法destroy()不会自动运行。

要想destory一个java bean对象有两者方式;

1.关闭spring容器:context.close();

context.close();

 

2.给Spring容器注册一个钩子:

context.registerShutdownHook();

 

无论init()和destroy()或者registerShutdownHook()的位置在哪里,init都会save()先执行.

destroy()或者registerShutdownHook()都会在save()方法执行完成之后执行。

 

--------------------------------------------------------使用Spring自带的方法---------------------------------------------------------------------------

如果一个java类型,实现了Spring的InitializingBean, DisposableBean两个接口,则这个java类也能管理bean的初始化和销毁。

Java Bean的destory和afterPropertiesSet()来自Spring.

实现了Spring 的两个接口:InitializingBean, DisposableBean

代码:

package com.oxygen.dao.impl;

import com.oxygen.dao.BookDao;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class BookDaoImpl implements BookDao, InitializingBean, DisposableBean {
    public void save() {
        System.out.println("Book Dao Save...");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println(" spring destroy....");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(" spring afterPropertiesSet....");
    }
}

 

posted on 2022-10-16 17:18  国王陛下万万岁  阅读(449)  评论(0编辑  收藏  举报