In a Spring-Boot application without web server, what is the correct way to keep it running?
Asked Answered
P

1

6

I have written a small spring-boot application without embedded servers. It is intended to run from command line and stay running until the VM gets signalled. What is the intended way of in the spring-boot framework (v2.0) to keep the application alive as a service? Should I have a Thread.currentThread().wait(); as last statement in my run(ApplicationArguments args) method? Is there an enabling annotation?

Plainsong answered 17/7, 2018 at 7:31 Comment(7)
Possible duplicate of How to prevent Spring Boot daemon/server application from closing/shutting down immediately?Chromomere
it indeed looks duplicate, but not conclusive, and likely outdated. Most hints look very hacky.Plainsong
System.in.read would block until the first key stroke... I want the thing just wait for Crtl-C.Plainsong
@Plainsong the solultion given in this answer seems the right approach https://mcmap.net/q/467094/-how-to-prevent-spring-boot-daemon-server-application-from-closing-shutting-down-immediately better than waiting for a key strokePlatonic
@Platonic That approach is bad as it will also work on all SpringBootTest tests. Hence those tests won't stop.Jaimie
The solution with adding an empty scheduled task seems the least hacky one. @Scheduled(fixedDelay = Long.MAX_VALUE) public void doNotShutdown() {} It even works with the most basic Spring Boot Starter.Jaimie
@SvenDöring you are right about that but if you are doing Unit Test without SpringBootTest this work. Enabling Scheduling is an idea. I didn't check but maybe since 2018 they are new solutions.Platonic
O
-2

from org.springframework.boot.web.embedded.netty.NettyWebServer, Official.

    private void startDaemonAwaitThread(DisposableServer disposableServer) {
        Thread awaitThread = new Thread("server") {

            @Override
            public void run() {
                disposableServer.onDispose().block();
            }

        };
        awaitThread.setContextClassLoader(getClass().getClassLoader());
        awaitThread.setDaemon(false);
        awaitThread.start();
    }
Orlon answered 25/5, 2020 at 11:38 Comment(2)
that kind of contradicts the question condition of having a Spring-Boot application without a webserver, doesn't it?Plainsong
I just assume there is another server instead of default web server, so it is necessary to keep application running. Refer to the official implementation, you can start a thread which blocked and waiting your server close.Orlon

© 2022 - 2024 — McMap. All rights reserved.