【问题标题】:Restarting Java Spring Boot Application重新启动 Java Spring Boot 应用程序
【发布时间】:2023-08-24 08:33:01
【问题描述】:

首先,我只想告诉您,我已经阅读了多种方法,但没有一种方法对我有用。我只需要在调用方法时重新启动应用程序。

到目前为止我所尝试的:

@Service
    public class RestartService {

        @Autowired
        private RestartEndpoint restartEndpoint;

        public void restartApp() {
            Thread restartThread = new Thread(() -> restartEndpoint.restart());
            restartThread.setDaemon(false);
            restartThread.start();
        }
    }

另一个:

@SpringBootApplication
public class RestfulWebservicesApplication {


private static ConfigurableApplicationContext context;

    public static void main(String[] args) throws IOException {
        SpringApplication.run(RestfulWebservicesApplication.class, args);


    }

    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);

        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(RestfulWebservicesApplication.class, args.getSourceArgs());
        });

        thread.setDaemon(false);
        thread.start();
    }
}

还有这个:

public class OneMoreRestart {

    @GetMapping("/restart")
    void restart() {
        Thread restartThread = new Thread(() -> {
            try {
                Thread.sleep(1000);
                Main.restart();
            } catch (InterruptedException ignored) {
            }
        });
        restartThread.setDaemon(false);
        restartThread.start();
    }

}

我也尝试了这里发布的方法: https://www.baeldung.com/java-restart-spring-boot-app

我已经尝试了我在谷歌或这里找到的所有方法,它们都不适合我......

我通常会得到空指针异常,我知道我是一个完整的菜鸟,但我从不认为重新启动应用程序可能如此困难。我在这里错过了什么或者我在这里做错了什么????

【问题讨论】:

  • 你能提供整个堆栈跟踪吗?说你得到了 npe 并不能提供任何信息。

标签: java spring spring-boot main restart


【解决方案1】:

你需要修改如下图

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

【讨论】:

  • nullPointers 之一,无论我使用什么,如果我尝试从网站重新启动,例如使用网站的 /restart 路径,或者我尝试在本地调用它```线程中的异常“线程-12" com.example.demo.RestartService.lambda$0(RestartService.java:20) 处 java.lang.Thread.run(未知来源)处的 java.lang.NullPointerException ```
  • 当我更改代码中的某些内容并单击 CNTRL+S 应用程序自动重启时,是否有可能从方法内以某种方式触发此重启或????????
  • 更正了您的答案。第一次运行后 ConfigurableApplicationContext 上下文中没有引用数据。
最近更新 更多