SpringBoot Shutdown Hook 原理

前言

  • 参考,https://blog.csdn.net/qq271859852/article/details/107548921
代码

看了其他文章,需要手动 applicationContext.registerShutdownHook();注册。
但是去掉后ShutdownHook依然生效,这是为什么呢,

我的测试代码如下:

@SpringBootApplication
public class SpringShutdownDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringShutdownDemoApplication.class, args);
        System.out.println("注册 registerShutdownHook!");
        applicationContext.registerShutdownHook();
    }
}

@Slf4j
@Component
public class DemoService {
    @PostConstruct
    public void init(){
        log.info("DemoService");
    }
    @PreDestroy
    public void preDestroy(){
        Eat.eat();
        log.info("preDestroy");
    }
}


public class Eat {
    public static void  eat(){
        StackTraceElement[] elements = Thread.currentThread().getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("index: ").append(i).append(" ClassName: ").append(elements[i].getClassName())
                    .append(" Method Name : " + elements[i].getMethodName());
            System.out.println(buffer.toString());
        }
        System.out.println("eat");
    }
}

自动注入解析

注释applicationContext.registerShutdownHook()
经查看,SpringApplication类 会自动维护 SpringApplicationShutdownHook

static final SpringApplicationShutdownHook shutdownHook = new SpringApplicationShutdownHook();

SpringApplicationShutdownHook类

class SpringApplicationShutdownHook implements Runnable {
	...
	SpringApplicationShutdownHook() {
		try {
			addRuntimeShutdownHook();
		}
		catch (AccessControlException ex) {
			// Not allowed in some environments
		}
	}
	...
	protected void addRuntimeShutdownHook() {
		Runtime.getRuntime().addShutdownHook(new Thread(this, "SpringApplicationShutdownHook"));
	}
	...
}
结论

至此,已经明白,SpringApplicationShutdownHook 会自动注册到 Runtime.getRuntime().addShutdownHook()
也就不需要我们手动注入,完

你可能感兴趣的:(SpringBoot)