背景: 最近工作在项目中需要添加多个守护线程,来处理一些功能,因此想通过Spring注解的方式开发一个这样的功能(直接setDaemon(true)也能开启守护线程,但是不够优雅,我是个优雅的人O(∩_∩)O哈哈~,anyway just joking)
介绍:
废话不多说先简单介绍一下这两个接口的作用 InitializingBean 与 DisposableBean是一对相爱相杀的好朋友,一个初始化,一个销毁.
InitializingBean有一个afterPropertiesSet方法,他的功能是在Bean实例化后且属性注入完成之后执行方法里面的代码.
DisposableBean有一个destroy方法,他的功能是在Bean销毁之前执行这个方法里面的代码,主要做收尾工作,比如我这里要做的时候当spring服务kill时通知守护线程关闭.
@Component
public class TopologyConsumer implements InitializingBean, DisposableBean, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(TopologyConsumer.class);
@Value("${server.daemon.sleep.consumer}")
private Long sleepSecs;
private volatile boolean condition = true;
@Override
public void run() {
while (condition) {
// 需要执行的代码
System.out.println("这里需要执行的代码");
}
}
/**
* condition字段自定义的 随便取一个就行 主要是给while条件判断的依据 服务关闭前会调用destroy方法
*
*/
@Override
public void destroy() throws Exception {
condition = false;
}
/**
* afterPropertiesSet() 方法在该Bean被实例化后属性注入完成之后执行里面的代码
* 这里是启动该线程(也就是前面说的守护线程)
*/
@Override
public void afterPropertiesSet() throws Exception {
new Thread(this).start();
}
}
很简单.