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>>>>");
}
你投入得越多,就能得到越多得价值