銷毀Spring Bean的三種方法


  • @PreDestroy Java標准注解
  • 實現DisposableBean的Destroy()方法
  • 自定義銷毀方法
    • XML 配置:<bean destroy="destroy" ... />
    • Java注解 @Bean(destroy="destroy")
    • Java API AbstractBeanDefinition#setDestroyMethodName(String)

DemoApplication.java

package com.rumenz;
public class DemoApplication {
    public static  void main(String[] args) {
        AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();
        ac.register(DemoApplication.class);
        ac.refresh();
        System.out.println("Spring 上下文啟動完成。。。。。");
        final DefaultRumenzFactory bean = ac.getBean(DefaultRumenzFactory.class);

        System.out.println("Spring 上下文准備關閉。。。。。");
        ac.close();
        System.out.println("Spring 上下文已關閉。。。。。");
    }
    @Bean(initMethod = "initMethod",destroyMethod = "destroy1")
    public static  DefaultRumenzFactory defaultRumenzFactory(){
        return new DefaultRumenzFactory();
    }
    @PreDestroy
    public void destroy(){
        System.out.println("PreDestroy執行。。。。");
    }
}

DefaultRumenzFactory.java

package com.rumenz;
public class DefaultRumenzFactory implements  InitializingBean, DisposableBean {

    public DefaultRumenzFactory() {
        System.out.println("無參構造方法執行....");
    }

    @PostConstruct
    public void init(){
        System.out.println("PostConstruct init.......");
    }
    public void initMethod(){
        System.out.println("init method.......");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet.....");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean#destroy 執行中。。。");
    }
    public void destroy1(){
        System.out.println("@Bean(destroyMethod = \"destroy1\") 自定義銷毀方法執行...");
    }
}

輸出

Spring 上下文准備關閉。。。。。
DisposableBean#destroy 執行中。。。
@Bean(destroyMethod = "destroy1") 自定義銷毀方法執行...
PreDestroy執行。。。。
Spring 上下文已關閉。。。。。

AnnotationConfigApplicationContext.close() 觸發了銷毀操作

源碼:https://github.com/mifunc/Spring-Bean-Destroy

原文: https://rumenz.com/rumenbiji/Spring-Bean-Destroy.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM