因爲項目須要,在系統啓動以後,要新起一條線程一直跑,用做監聽器,使用回調方法處理將要發生的事情,處理時,須要用到 JPA 的接口。java
所以,須要設置一條守護線程,而且能夠自動裝配 Spring Bean,採用第三個方法。app
方案一ide
@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); } }
方案二this
@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); } }
方案四code
ApplicationRunner 接口