如何停止正在启动的 Spring Boot 应用程序?

boo*_*oop 2 java spring spring-boot

是否可以在 Spring Boot 应用程序旋转时停止它?

我的软件需要在启动时验证许可证。如果许可证不存在或无效,应用程序将关闭。实际的验证发生@PostConstruct@Service.

我目前走的路是:

if (!exist || !valid) {
    System.exit(1);
}
Run Code Online (Sandbox Code Playgroud)

但这个解决方案感觉很糟糕。有没有一种解决方案可以在不调用 REST 端点的情况下停止 Spring Boot 应用程序?

M. *_*num 5

假设您的代码位于组件中(或者 Spring 检测到的 bean)。您可以简单地ApplicationContext在退出调用之前注入 and close

public class LicenseChecker {

    @Autowired
    private ApplicationContext ctx;

    public void check() {
        if (!exist || !valid) {
            ((ConfigurableApplicationContext) ctx).close();
            System.exit(1);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)