Spring Bean 的 destroy方法配置

本文探讨了在Spring框架中如何通过实现InitializingBean接口、使用@PostConstruct和@PreDestroy注解,以及定义init-method和destroy-method属性来管理Bean的生命周期。通过实例展示了如何创建和销毁临时文件。

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

import java.io.File;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DestructiveBean implements InitializingBean {
    private File file;
    private String filePath;
    public void afterPropertiesSet() throws Exception {
        System.out.println("Initializing  Bean");
        if (filePath == null) {
            throw new IllegalArgumentException(
                    "You must specify the filePath property of"
                        + DestructiveBean.class);
        }
        this.file = new File(filePath);
        this.file.createNewFile();
        System.out.println("File exists: " +  file.exists());
    }
    public void destroy() {
        System.out.println("Destroying  Bean");
        if(!file.delete()) {
            System.err.println("ERROR: failed  to delete file.");
        }
        System.out.println("File exists: " + file.exists());
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public static void main(String... args) throws Exception {
        GenericXmlApplicationContext ctx =
            new GenericXmlApplicationContext();
        ctx.load("classpath:spring/app-context-xml.xml");
        ctx.refresh();
        DestructiveBean bean = (DestructiveBean) ctx.getBean("destructiveBean");
        System.out.println("Calling destroy()");
        ctx.destroy();
        System.out.println("Called destroy()");
    }
}

利用InitializingBean设置destroy方法


<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="destructiveBean"
        class="com.apress.prospring5.ch4.DestructiveBean"
        destroy-method="destroy"
        p:filePath=
   "#{systemProperties'java.io.tmpdir'}#{systemProperties'file.separator'}test.txt"/>
</beans>

xml配置文件设置destroy方法

import java.io.File;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DestructiveBeanWithInterface implements InitializingBean, DisposableBean {
    private File file;
    private String filePath;
    @Override
    public void afterPropertiesSet()  throws Exception {
        System.out.println("Initializing  Bean");
        if (filePath == null) {
            throw new IllegalArgumentException(
                    "You must  specify the filePath property of " +
                    DestructiveBeanWithInterface.class);
        }
        this.file = new File(filePath);
        this.file.createNewFile();
        System.out.println("File exists: " +  file.exists());
    }
    @Override
    public void destroy() {
        System.out.println("Destroying  Bean");
        if(!file.delete()) {
            System.err.println("ERROR: failed  to delete file.");
        }
        System.out.println("File exists: " +  file.exists());
    }
    public void setFilePath(String filePath)  {
        this.filePath =  filePath;
    }
    public static void main(String... args) throws Exception {
        GenericXmlApplicationContext  ctx  =
            new GenericXmlApplicationContext();
        ctx.load("classpath:spring/app-context-xml.xml");
        ctx.refresh();
        DestructiveBeanWithInterface bean =
            (DestructiveBeanWithInterface) ctx.getBean("destructiveBean");
        System.out.println("Calling destroy()");
        ctx.destroy();
        System.out.println("Called destroy()");
    }
}

通过Disposable interface设置destroy 方法

import java.io.File;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DestructiveBeanWithJSR250 {
    private File file;
    private String filePath;
    @PostConstruct
    public void afterPropertiesSet()  throws Exception {
        System.out.println("Initializing  Bean");
        if (filePath == null) {
            throw new IllegalArgumentException(
                    "You must specify the filePath property of " +
                    DestructiveBeanWithJSR250.class);
        }
        this.file = new File(filePath);
        this.file.createNewFile();
        System.out.println("File exists: " +  file.exists());
    }
    @ PreDestroy
    public void destroy() {
        System.out.println("Destroying  Bean");
        if(!file.delete()) {
            System.err.println("ERROR: failed  to delete file.");
        }
        System.out.println("File exists: " +  file.exists());
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public static void main(String... args) throws Exception {
        GenericXmlApplicationContext  ctx  =
            new GenericXmlApplicationContext();
        ctx.load("classpath:spring/app-context-annotation.xml");
        ctx.refresh();
        DestructiveBeanWithJSR250 bean  =
            (DestructiveBeanWithJSR250) ctx.getBean("destructiveBean");
        System.out.println("Calling destroy()");
        ctx.destroy();
        System.out.println("Called destroy()");
    }
}

@PreDestroy设置destroy方法

@Lazy
            @Bean(initMethod = "afterPropertiesSet", destroyMethod = "destroy")
             DestructiveBeanWithJSR250 destructiveBean() {
                 DestructiveBeanWithJSR250 destructiveBean  =
                            new DestructiveBeanWithJSR250();
                 destructiveBean.setFilePath(System.getProperty("java.io.tmpdir") +
                         System.getProperty("file.separator") +  "test.txt");
                   return  destructiveBean;
                 }

注解Bean配置destroy方法

public class DestructiveBeanWithHook {
   public static void main(String... args) {
        GenericApplicationContext ctx =
           new AnnotationConfigApplicationContext(
               DestructiveBeanConfig.class);
           ctx.getBean(DestructiveBeanWithJSR250.class);
           ctx.registerShutdownHook();
   }
}

shut down 程序时,调用destroy方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值