Programmatically restart Spring Boot application / Refresh Spring Context

后端 未结 6 1612
佛祖请我去吃肉
佛祖请我去吃肉 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:09

    As was commented already, the restart-via-thread implementations given before only work once, and second time around throw a NPE because context is null.

    This NPE can be avoided by having the restart thread use the same class loader as the initial main-invoking thread:

    private static volatile ConfigurableApplicationContext context;
    private static ClassLoader mainThreadClassLoader;
    
    public static void main(String[] args) {
        mainThreadClassLoader = Thread.currentThread().getContextClassLoader();
        context = SpringApplication.run(Application.class, args);
    }
    
    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);
    
        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(Application.class, args.getSourceArgs());
        });
    
        thread.setContextClassLoader(mainThreadClassLoader);
        thread.setDaemon(false);
        thread.start();
    }
    

提交回复
热议问题