深入Spring专题(30)

123 阅读1分钟

这是我参与2022首次更文挑战的第37天,活动详情查看2022首次更文挑战

在bean被销毁时执行一个方法

​ 如果想要指定一个在bean被销毁时调用的方法,只需要在bean的标记的destroy-method属性中指定该方法的名称即可。Spring在销毁bean的单例实例之前会调用该方法。

使用destroy-method回调代码如下:

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("你必须定义文件目录属性的值:"+DestructiveBean.class);
        }
        this.file=new File(filePath);
        this.file.createNewFile();
        System.out.println("文件存在:"+file.exists());
    }
    public void destroy(){
        System.out.println("Destroying Bean");
        if(!file.delete()){
            System.out.println("删除文件失败!");
        }
        System.out.println("文件存在:"+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");
        ctx.refresh();
        
        DestructiveBean bean=(DestructiveBean)ctx.getBean("destructiveBean");
        System.out.println("调用bean销毁方法开始");
        ctx.destroy();
        System.out.println("调用bean销毁方法结束");
    }
   
}

定义一个destroy()方法,用来删除所创建的文件。main()方法从GenericXmlApplicationContext中检索一个类型为DestructiveBean的bean,然后调用它的destroy()方法(并且依次调用由ApplicationContext封装的ConfigurableBeanFactory.destroySingleton()),指示Spring销毁它所管理的所有单例。初始化回调和销毁回调都会向控制台输出一条消息,告知它们已被调用。

配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmls=“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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd" >
	
    <bean id="destructiveBean" class="com.ozx.DestructiveBean" destroy-method="destroy" p:filePath="#{systemProperties}/test.txt"/>
</beans>

注意点:

​ 通过使用destroymethod属性指定destroy()方法作为销毁回调。filePath属性值是使用SpEL表达式构建的,在文件名test.txt之前将系统属性和file.separator连接起来以保证跨平台兼容性。

运行代码得到如下结果:

Initializing Bean
文件存在:true
调用bean销毁方法开始
Destroying Bean
文件存在:false
调用bean销毁方法结束