Programmatically shut down Spring Boot application

前端 未结 5 1234
误落风尘
误落风尘 2020-11-27 13:52

How can I programmatically shutdown a Spring Boot application without terminating the VM?

In other works, what is

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 14:34

    The simplest way would be to inject the following object where you need to initiate the shutdown

    ShutdownManager.java

    import org.springframework.context.ApplicationContext;
    import org.springframework.boot.SpringApplication;
    
    @Component
    class ShutdownManager {
    
        @Autowired
        private ApplicationContext appContext;
    
        /*
         * Invoke with `0` to indicate no error or different code to indicate
         * abnormal exit. es: shutdownManager.initiateShutdown(0);
         **/
        public void initiateShutdown(int returnCode){
            SpringApplication.exit(appContext, () -> returnCode);
        }
    }
    

提交回复
热议问题