由于项目需要,在系统启动之后,要新起一条线程一直跑,用作监听器,使用回调方法处理将要发生的事情,处理时,需要用到 JPA 的接口。
因此,需要设置一条守护线程,并且可以自动装配 Spring Bean,采用第三个方法。
方案一
@SpringBootApplication
public class App {
//发射App
public static void main(String[] args) {
Thread thread = new Thread();
thread.setDaemon(true);
thread.start();
SpringApplication app = new SpringApplication(App.class);
app.run(args);
}
}
方案二
@Bean
class EventSubscriber implements DisposableBean, Runnable {
private Thread thread;
private volatile boolean someCondition;
EventSubscriber(){
this.thread = new Thread(this);
}
@Override
public void run(){
while(someCondition){
doStuff();
}
}
@Override
public void destroy(){
someCondition = false;
}
}
方案三
@Component
public class Listener implements ApplicationListener<ContextRefreshedEvent>, Runnable {
@Autowired
IUserRepo userRepo;//使用Spring data jpa,接口,没办法实现,只能让Spring自动装配
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Listener listener = event.getApplicationContext().getBean(Listener.class);
new Thread(this).start();
}
@Override
public void run() {
System.out.println("run run run...");
}
}
@SpringBootApplication
public class App {
//发射App
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.setListeners(new Listener());
app.run(args);
}
}
方案四
ApplicationRunner