I have a Spring Boot application deployed in Tomcat 8. When the application starts I want to start a worker Thread in the background that Spring Autowires with some dependencies. Currently I have this :
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class MyServer extends SpringBootServletInitializer {
public static void main(String[] args) {
log.info("Starting application");
ApplicationContext ctx = SpringApplication.run(MyServer.class, args);
Thread subscriber = new Thread(ctx.getBean(EventSubscriber.class));
log.info("Starting Subscriber Thread");
subscriber.start();
}
In my Docker test environment this works just fine - but when I deploy this to my Linux (Debian Jessie, Java 8) host in Tomcat 8 I never see the "Starting Subscriber Thread" message (and the thread is not started).
The main method is not called when deploying the application to a non-embedded application server. The simplest way to start a thread is to do it from the beans constructor. Also a good idea to clean up the thread when the context is closed, for example:
You could have a bean which impelements
ApplicationListener<ContextRefreshedEvent>
It'sonApplicationEvent
will be called just start your thread there if it hasn't been started already. I think you want the ApplicationReadyEvent by the way.Edit How to add a hook to the application context initialization event?