Programmatically restart Spring Boot application / Refresh Spring Context

后端 未结 6 1588
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 15:43

I am trying to programmatically restart my Spring Application without having the user to intervene.

Basically, I have a page which allows to switch the mode of the a

6条回答
  •  遥遥无期
    2020-12-03 16:10

    In case it might help someone, here's a pura Java translation of Crembo's accepted answer.

    Controller method:

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

    Main class (significant bits only):

    private static String[] args;
    private static ConfigurableApplicationContext context;
    
    public static void main(String[] args) {
        Main.args = args;
        Main.context = SpringApplication.run(Main.class, args);
    }
    
    public static void restart() {
        // close previous context
        context.close();
    
        // and build new one
        Main.context = SpringApplication.run(Main.class, args);
    
    }
    

提交回复
热议问题