How to prevent Spring app context shutdown until shutdown hook is fired
<p>I have a spring-boot application.</p>

<p>I have implemented <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html" rel="noreferrer"><code>SmartLifecycle</code></a> interface in my bean which starts async snmp server in it's <code>start</code> method and stops it in it's <code>stop</code> method.</p>

<p>All working fine, except the fact that main application context stops right after start, so my server bean also stops right after start.</p>

<p>All I need is to make spring context to stop only when shutdown hook is fired.</p>

<p>This is not a web application, so I don't need <code>spring-boot-starter-web</code>, which is solves this problem by starting webserver which prevents context stop until webserver stops.</p>

<p>I can use something like <code>CountDownLatch</code> and waiting for it to be zero in my <code>main</code> method right after context starts. Somethig like this:</p>

<pre><code>public static void main(String[] args) throws InterruptedException {
    ConfigurableApplicationContext ctx = SpringApplication.run(SnmpTrapRetranslatorApplication.class, args);
    CountDownLatch snmpServerCloseLatch = ctx.getBean("snmpServerCloseLatch", CountDownLatch.class);
    snmpServerCloseLatch.await();
}
</code></pre>

<p>And my server bean's <code>start</code> method will create this latch with count <code>1</code>, while <code>stop</code> method will call <code>snmpServerCloseLatch.countDown()</code>.</p>

<p>This technique is described <a href="https://spring.io/guides/gs/reactor-thumbnailer/" rel="noreferrer">here</a>.</p>

<p>But what wrong with this is that my <code>main</code> method is responsible for waiting my custom server bean to stop. I feel this just not right.</p>

<p>How for example <code>spring-boot-starter-web</code> 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 <code>main</code> method. It stops only when context receiving shoutdown signal.</p>

<p>The same behaviour is for example when I have <code>@Scheduled</code> method in my bean. Spring also doesn't stops context automatically. Only on <code>CTRL-C</code>.</p>

<p>I want to achieve similar effect. My <code>main</code> 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 <code>SmartLifecycle</code>) and should not stop until shutdown is requested (CTRL-C, SIGINT etc).</p>