在项目启动后执行一些初始化操作CommandLineRunner
SpringBoot中CommandLineRunner的作用
平常开发中有可能需要实现在项目启动后执行的功能,SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口,实现功能的代码放在实现的run方法中 也就是项目一启动之后,就立即需要执行的动作
代码示例
/**
* @author jijiecong
* @version 1.0
* @date 2022/4/25 16:57
* @description TODO
*/
@Component
@Slf4j
public class RedisCacheInit implements CommandLineRunner {
@Resource
TransferServiceImpl transferService;
@Resource
EsIndexPropertyServiceImpl esIndexPropertyService;
private RedisCacheInitConfig redisCacheInitConfig = SpringUtil.getBean(RedisCacheInitConfig.class);
/**
* 启动后自动清除redis缓存的索引数据:property和transfer
*/
@Override
public void run(String... args) throws Exception {
log.info("清除redis缓存的索引配置开始");
List<String> indexList = redisCacheInitConfig.getIndexList();
if (CollectionUtils.isEmpty(indexList)) {
return;
}
for (String index: indexList) {
esIndexPropertyService.clearPropertyCache(index);
for (BizSourceEnum bizSourceEnum: BizSourceEnum.values()) {
transferService.clearTransferIndexCache(index, String.valueOf(bizSourceEnum.getCode()));
}
}
log.info("清除redis缓存的索引配置结束");
}
}
补充
如果需要多个执行类,且有先后依赖顺序,可使用@Order注
posted on 2022-04-26 11:11 Iversonstear 阅读(125) 评论(0) 编辑 收藏 举报