spring对象的两种销毁方法

spring有两种销毁方法,第一种是实现DisposableBean接口,另一种是使用destroy-method标签,具体代码如下:

1、新建destoryProduct测试类

package product;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class destoryProduct implements InitializingBean, DisposableBean {

    //第一种,spring自带的销毁方法
    public void destroy() throws Exception {
        System.out.println("spring对象的销毁方法。。。。。。。。。。。。。");
    }
    //第二种,spring对象的自己写的销毁方法
    public void destoryByMyself(){
        System.out.println("spring对象的自己写的销毁方法。。。。。。。。。。。。。");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("spring对象的初始化方法。。。。。。。。。。。。。。。。。。");
    }


}

2、applicationConxtex.xml文件中添加如下配置

<bean id="destoryProduct" class="product.destoryProduct" destroy-method="destoryByMyself"/>

3.执行test类,看执行效果

@Test
public void test8(){
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
    ctx.close();
}

以上就是spring销毁的两种方式

经验分享 程序员 微信小程序 职场和发展