Programmatically shut down Spring Boot application

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

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

In other works, what is

5条回答
  •  猫巷女王i
    2020-11-27 14:17

    In the application you can use SpringApplication. This has a static exit() method that takes two arguments: the ApplicationContext and an ExitCodeGenerator:

    i.e. you can declare this method:

    @Autowired
    public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
        SpringApplication.exit(applicationContext, exitCodeGenerator);
    }
    

    Inside the Integration tests you can achieved it by adding @DirtiesContext annotation at class level:

    • @DirtiesContext(classMode=ClassMode.AFTER_CLASS) - The associated ApplicationContext will be marked as dirty after the test class.
    • @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD) - The associated ApplicationContext will be marked as dirty after each test method in the class.

    i.e.

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = {Application.class},
        webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"server.port:0"})
    @DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
    public class ApplicationIT {
    ...
    

提交回复
热议问题