I have a spring-boot application.
I have implemented SmartLifecycle
interface in my bean which starts async snmp server in it's start
method and stops it in it's stop
method.
All working fine, except the fact that main application context stops right after start, so my server bean also stops right after start.
All I need is to make spring context to stop only when shutdown hook is fired.
This is not a web application, so I don't need spring-boot-starter-web
, which is solves this problem by starting webserver which prevents context stop until webserver stops.
I can use something like CountDownLatch
and waiting for it to be zero in my main
method right after context starts. Somethig like this:
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext ctx = SpringApplication.run(SnmpTrapRetranslatorApplication.class, args);
CountDownLatch snmpServerCloseLatch = ctx.getBean("snmpServerCloseLatch", CountDownLatch.class);
snmpServerCloseLatch.await();
}
And my server bean's start
method will create this latch with count 1
, while stop
method will call snmpServerCloseLatch.countDown()
.
This technique is described here.
But what wrong with this is that my main
method is responsible for waiting my custom server bean to stop. I feel this just not right.
How for example spring-boot-starter-web
do this? When it starts tomcat, it keeps running until shutdown hook is received and it don't need to have any managing code in the main
method. It stops only when context receiving shoutdown signal.
The same behaviour is for example when I have @Scheduled
method in my bean. Spring also doesn't stops context automatically. Only on CTRL-C
.
I want to achieve similar effect. My main
method should have only one line: start the context. Context should start and stop my async server when it starts or stops (already achieved by SmartLifecycle
) and should not stop until shutdown is requested (CTRL-C, SIGINT etc).