深入Spring专题(32)

86 阅读1分钟

这是我参与2022首次更文挑战的第39天,活动详情查看2022首次更文挑战 bean的配置文件如下:

<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" >
	<context:annotation-config/>
    <bean id="destructiveBean" class="com.ozx.DestructiveBean" destroy-method="destroy" p:filePath="#{systemProperties}/test.txt"/>
</beans>

使用@Bean声明销毁方法

声明bean的销毁方法的另一种方式是为@Bean注解指定destroyMethod属性,并将销毁方法的名称设置为该属性的值,该注解用于在Java配置类中声明bean。

编写一个配置类和一个main()方法来测试它,配置是外部的,类似使用了destroy-method属性一样,default-lazy-init="true"将被替换为@Lazy注解。

public class DestructiveBeanConfigDemo{
    static class DestructiveBeanConfig{
        
        @Lazy
        @Bean(initMethod="afterPropertiesSet",destroyMethod="destroy")
        DestructiveBean destructiveBean(){
            DestructiveBean destructiveBean=new DestructiveBean();
  destructiveBean.setFilePath(System.getProperty("java.io.tmpdir"+System.getProperty("file.separator")+"test.txt");
         return  destructiveBean;                             )
        }
        
        public static void main(String... args){
            GenericApplicationContext ctx=new AnnotationConfigApplicationContext(DestructiveBeanConfig.class);
            ctx.getBean(DestructiveBean.class);
            System.out.println("调用bean销毁方法开始");
        	ctx.destroy();
        	System.out.println("调用bean销毁方法结束");
        }
    }
}

运行结果如下:

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

销毁回调是确保应用正常关闭并且不使资源处于打开或不一致状态的理想机制,但是需要决定是使用销毁方法回调、Disposable接口、@PreDestroy注解、Xml destroy-attribute属性还是destroyMethod,使用哪种方式需要根据应用需求来决定的,当需要考虑可移植性问题时使用方法回调,同时可以使用DisposableBean接口或JSR-250注解来减少所需的配置量。

销毁bean解析的顺序

在同一bean实例上使用所有机制来进行bean销毁,这种情况下,Spring首先调用拥@PreDestroy注解的方法,然后调用DisposableBean.destroy(),最后调用XML定义配置的destroy()方法。