My Spring Boot application is not a web server, but it's a server using custom protocol (using Camel in this case).
But Spring Boot immediately stops (gracefully) after started. How do I prevent this?
I'd like the app to stop if Ctrl+C or programmatically.
@CompileStatic @Configuration class CamelConfig { @Bean CamelContextFactoryBean camelContext() { final camelContextFactory = new CamelContextFactoryBean() camelContextFactory.id = 'camelContext' camelContextFactory } }
In the Spring Boot Document, they said that 'Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. ' When I click ctrl+c on the shell command, the application can be shutdown gracefully.
Spring Boot Actuator comes with many production-ready features which include /shutdown endpoint. By default, all /shutdown endpoint is not enabled in the Actuator. To use this endpoint in our application, we should include spring-boot-starter-actuator starter and enable this endpoint in our application.
We know that a Spring Boot web app needs an embedded servlet container on the classpath. The app will shut down if it doesn't find any of the embedded servlet containers. To resolve the unexpected shut down during startup, we need to obtain a fully configured instance using the appropriate Starter.
I found the solution, using org.springframework.boot.CommandLineRunner
+ Thread.currentThread().join()
, e.g.: (note: code below is in Groovy, not Java)
package id.ac.itb.lumen.social import org.slf4j.LoggerFactory import org.springframework.boot.CommandLineRunner import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class LumenSocialApplication implements CommandLineRunner { private static final log = LoggerFactory.getLogger(LumenSocialApplication.class) static void main(String[] args) { SpringApplication.run LumenSocialApplication, args } @Override void run(String... args) throws Exception { log.info('Joining thread, you can press Ctrl+C to shutdown application') Thread.currentThread().join() } }
As of Apache Camel 2.17 there is a cleaner answer. To quote http://camel.apache.org/spring-boot.html:
To keep the main thread blocked so that Camel stays up, either include the spring-boot-starter-web dependency, or add camel.springboot.main-run-controller=true to your application.properties or application.yml file.
You will want the following dependency too:
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>2.17.0</version> </dependency>
Clearly replace <version>2.17.0</version>
or use the camel BOM to import dependency-management information for consistency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With