以编程方式重新启动Spring Boot应用程序

12

我正在使用Spring Boot,有一个使用案例需要用户上传文件后重启应用程序(因为在创建多个bean时会使用用户的上传文件)。 我知道我可以避免重新启动应用程序,但目前 - 这就是我想要的。

我在Spring-Cloud项目中找到了RestartEndpoint,但似乎没有触发ApplicationPreparedEvent。 除了这种方式,我还能以编程方式重新启动Spring Boot应用程序吗?

4个回答

3
最简单的方法是调用Spring ApplicationContext上的refresh()方法。这将杀死并重新加载所有bean,因此您应该确保仅在应用程序安全时才进行此操作。

我已经尝试过了,但似乎不起作用,我得到了java.lang.IllegalStateException: GenericApplicationContext不支持多次刷新尝试:只需调用“refresh”一次即可。另请参阅此问题:https://dev59.com/fWAf5IYBdhLWcg3wXhyz - yglodt
在Spring Boot中,某些应用程序上下文无法刷新。这将导致非法状态异常。 - Neha Agarwal

3

我有一个特殊的情况,我的Spring Boot应用程序在Linux上运行,需要以root身份运行。

由于我将应用程序作为systemd服务运行,因此可以像这样重新启动它:

Runtime.getRuntime().exec(new String[] { "/bin/systemctl", "restart", "foo" });

如果您的应用程序(希望如此)不需要以root身份运行,则可以使用setuid包装脚本,或者更好地,使用sudo。请参考以下回答了解如何实现:https://superuser.com/questions/440363/can-i-make-a-script-always-execute-as-root

1

好的,我没有使用Spring Cloud。 :) - Matija Folnovic

0

我使用下面的代码来从代码本身重新启动我的应用程序。使用单独的线程关闭上下文不会关闭JVM。

public class DemoApplication {

private static String[] args;
private static ConfigurableApplicationContext context;

public static void main(String[] args) {
    DemoApplication.args = args;
    context = SpringApplication.run(DemoApplication.class, args);
}

public static void restart() {
  
    Thread thread = new Thread(() -> {
        context.close();            
        context = SpringApplication.run(DemoApplication.class, DemoApplication.args);
    });
    thread.setDaemon(false);
    thread.start();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接