我已经部署在Tomcat的8 Spring的启动应用程序应用程序启动时我想的背景下,春节Autowires有一些依赖,开始工作线程。目前,我有这样的:
@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();
}
在我的码头工人的测试环境中,这工作得很好 - 但是当我部署此给Tomcat 8我的Linux(Debian的杰西,爪哇8)主机我从来没有看到“正在启动用户线程”的消息(和线程不启动)。
将应用程序部署到非嵌入式应用服务器时的主要方法不被调用。启动一个线程的最简单方法是从豆类构造做到这一点。也是一个不错的主意,清理线程时的背景是封闭的,例如:
@Component
class EventSubscriber implements DisposableBean, Runnable {
private Thread thread;
private volatile boolean someCondition;
EventSubscriber(){
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void run(){
while(someCondition){
doStuff();
}
}
@Override
public void destroy(){
someCondition = false;
}
}
你可以有哪些impelements ApplicationListener<ContextRefreshedEvent>
这是onApplicationEvent
将被称为刚开始你的线程有如果它尚未启动的bean。我想你想顺便ApplicationReadyEvent。
编辑How to add a hook to the application context initialization event?
@Component
public class FooBar implements ApplicationListener<ContextRefreshedEvent> {
Thread t = new Thread();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (!t.isAlive()) {
t.start();
}
}
}