SpringBoot之CommandLineRunner与App

2020-01-12  本文已影响0人  fanderboy

CommandLineRunner和ApplicationRunner是Spring Boot所提供的接口,他们都有一个run()方法。所有实现他们的Bean都会在Spring Boot服务启动之后自动地被调用。

由于这个特性,它们是一个理想地方去做一些初始化的工作。

CommandLineRunner和ApplicationRunner的作用是相同的。不同之处在于CommandLineRunner接口的run()方法接收String数组作为参数,而ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数。当程序启动时,我们传给main()方法的参数可以被实现CommandLineRunner和ApplicationRunner接口的类的run()方法访问。我们可以创建多个实现CommandLineRunner和ApplicationRunner接口的类。为了使他们按一定顺序执行,可以使用@Order注解或实现Ordered接口。

这篇文章只介绍下ApplicationRunner的使用方法,CommandLineRunner类似。

使用方法:使用@Component注解实现ApplicationRunner的类。

@Component
public class RedisInitRunner implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(RedisInitRunner.class);
    @Autowired(required = false)
    private GTSCacheProperties properties;
    @Autowired
    private CacheService cacheService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("初始化Redis数据开始…");
        long count = cacheService.deleteByPrefix(RedisKeyPrefixConstant.PROGRESS_PREFIX);
        logger.info("初始化Redis数据结束,共删除前缀[{}]{}条数据", properties.getPrefix() + RedisKeyPrefixConstant.PROGRESS_PREFIX, count);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读