Spring boot 守护线程

由于项目需要,在系统启动之后,要新起一条线程一直跑,用作监听器,使用回调方法处理将要发生的事情,处理时,需要用到 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 

 

转载于:https://my.oschina.net/u/3035165/blog/919492

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值