Spring应用手册-DisposableBean接口

本文详细介绍了Spring框架中DisposableBean接口的作用及使用方法,通过具体示例对比了配置文件中destroy-method属性与DisposableBean接口中destroy方法的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注

DisposableBean接口

spring应用手册(第五部分)


DisposableBean接口和InitializingBean接口一样,为bean提供了释放资源方法的方式,它只包括destroy方法,凡是继承该接口的类,在bean被销毁之前都会执行该方法。

这里要注意这里的destory和我们配置的destory-method不是一回事。

我们看一个测试案例:

我们个Coder添加destory方法,并且让其实现接口DisposableBean:

/**
 * @author 戴着假发的程序员
 * @company http://www.boxuewa.com
 * @description
 */
public class Coder implements DisposableBean {
    //构造方法
    public Coder(){
        System.out.println("实例化Coder对象");
    }
    //我们自己定义的 destory方法
    public void assignDestory(){
        System.out.println("我们自己定义的释放资源的方法执行");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean中的destroy方法执行");
    }
}

我们在配置文件中配置Coder,并且注明我们的destory-method:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 正常配置colder,配置destroy-method为assignDestory -->
    <bean id="coder" destroy-method="assignDestory" class="com.igeek.dk.demo10.beans.Coder"/>
</beans>

测试:

@Test
public void testDisposableBean(){
    ClassPathXmlApplicationContext ac =
            new ClassPathXmlApplicationContext("applicationContext-demo10.xml");
    //关闭容器
    ac.close();
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴着假发的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值