0

I'm trying to use a routing to stop my spring boot application with the code below with

@GetMapping("/close/")
    fun terminate() {
        exitProcess(0)
    }

but the test server has a different API, so I can't use this code (It's shutdown a whole system)

My question is: how to stop only my spring boot application (replace exitProcess(0))

Osvald Laurits
  • 1,228
  • 2
  • 17
  • 32
Viibration
  • 13
  • 3
  • add the actuator and invoke the `shutdown` endpoint instead of inventing your own. If you really want invoke `close` on the application context. See the [`ShutdownEndpoint`](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java) on how Spring itself does it. – M. Deinum Jun 22 '20 at 10:01

1 Answers1

1

You can do it using Actuator's shutdown for example. Find an example here.

Or you can just close your Application Context and that will work.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SomeRestController {

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("/close")
    public void terminate() {
        ((AbstractApplicationContext)applicationContext).close();
    }
}
  • Is there another way to stop application by routing without change a config? – Viibration Jun 23 '20 at 09:27
  • Yes, actually you can close your ApplicationContext and that will work. You just have to downcast it. Example: `((AbstractApplicationContext)applicationContext).close();` – André Nunes Jun 24 '20 at 19:31
  • Thanks, thats really help me a lot. By the way is there a way to restart app in the same way of `((AbstractApplicationContext)applicationContext).close()` now I only use `context = SpringApplication.run(Application::class.java, *args.sourceArgs)` in `val thread = Thread(Runnable { })`, `thread.isDaemon = false`, `thread.start()` with your `.close()` but I dont want to use thread because weblogic on test server cant control it, and without thread my `.run` will not start Application too. – Viibration Jul 03 '20 at 09:21
  • You can use actuator to do that. Or you can just run a thread to close and start your context again. You can check a really good example [here](https://www.baeldung.com/java-restart-spring-boot-app) – André Nunes Jul 03 '20 at 10:39