Spring容器关闭前执行销毁方法的几种方式

1、DisposableBean

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DisposableBeanDemo implements DisposableBean {
@Override
public void destroy() throws Exception {
log.info("invoke destroy");
}
}

 

2、SmartLifecycle

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SmartLifecycleDemo implements SmartLifecycle {
private boolean running;

@Override
public void start() {
log.info("start >>>>");
running = true;
}

@Override
public void stop() {
log.info("stop >>>>");
}

@Override
public boolean isRunning() {
return running;
}

@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
}

 

3、使用InitializingBean设置钩子函数addShutdownHook

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

@Slf4j
public class InitializingBeanDemo implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("addShutdownHook>>>>>");

}));
}
}

 

4、@PreDestroy注解

    @PreDestroy
    public void preDestroy(){
        log.info("PreDestroy>>>>");
    }

 

posted @ 2023-03-06 00:21  N!CE波  阅读(632)  评论(0编辑  收藏  举报