zoukankan      html  css  js  c++  java
  • (转)SpringBoot之退出服务(exit)时调用自定义的销毁方法

    我们在工作中有时候可能会遇到这样场景,需要在退出容器的时候执行某些操作。SpringBoot中有两种方法可以供我们来选择(其实就是spring中我们常用的方式。只是destory-method是在XML中配置的,SpringBoot是去配置化。所以这里就不提这种方式了),一种是实现DisposableBean接口,一种是使用@PreDestroy注解。OK,下面我写两个例子看一下:

    DisposableBean接口

    我们可以通过实现这个接口来在容器退出的时候执行某些操作。例子如下:
    package com.zkn.learnspringboot.destory;  
      
    import org.springframework.beans.factory.DisposableBean;  
    import org.springframework.boot.ExitCodeGenerator;  
    import org.springframework.stereotype.Component;  
      
    /** 
     * Created by zkn on 2016/8/14. 
     */  
    @Component  
    public class TestImplDisposableBean implements DisposableBean, ExitCodeGenerator {  
      
        @Override  
        public void destroy() throws Exception {  
      
            System.out.println("<<<<<<<<<<<我被销毁了......................>>>>>>>>>>>>>>>");  
            System.out.println("<<<<<<<<<<<我被销毁了......................>>>>>>>>>>>>>>>");  
        }  
      
        @Override  
        public int getExitCode() {  
      
            return 5;  
        }  
    }  
    @PreDestroy注解
    我们可以在需要的类的方法上添加这个注解,同样可以满足我们的需求。
    package com.zkn.learnspringboot.destory;  
      
    import org.springframework.stereotype.Component;  
    import javax.annotation.PreDestroy;  
      
    /** 
     * Created by zkn on 2016/8/14. 
     */  
    @Component  
    public class TestAnnotationPreDestroy {  
      
        @PreDestroy  
        public void destory() {  
      
            System.out.println("我被销毁了、、、、、我是用的@PreDestory的方式、、、、、、");  
            System.out.println("我被销毁了、、、、、我是用的@PreDestory的方式、、、、、、");  
        }  
    }  

    输出结果如下:

    TIPS:

    退出你可以通过Ide中的功能来退出。这里我启动的时候是在CMD中用jar启动的,启动命令如下:java -jar LearnSpringBoot-0.0.1-SNAPSHOT.jar,所以我在这里退出的时候是用的Ctrl+C来执行的退出操作。如果你用的mvn spring-boot:run来启动运行的话,可能不会执行销毁的操作。
     
  • 相关阅读:
    codeforces 669C C. Little Artem and Matrix(水题)
    codeforces 669B B. Little Artem and Grasshopper(水题)
    oracle drop table recyclebin恢复
    odu恢复drop表--不通过logmnr挖掘object_id
    odu恢复drop表--通过logmnr挖掘object_id
    odu恢复delete 表
    GO学习-(7) Go语言基础之流程控制
    GO学习-(6) Go语言基础之运算符
    GO学习-(4) Go语言基础之变量和常量
    GO学习-(3) VS Code配置Go语言开发环境
  • 原文地址:https://www.cnblogs.com/zhangmingcheng/p/8340150.html
Copyright © 2011-2022 走看看