Spring Boot 系统启动任务

作者阿里云代理 文章分类 分类:linux图文教程 阅读次数 已被围观 406

1. 背景

有时候我们会希望在Spring Boot项目启动时,完成一些初始化工作。


例如加载初始化的缓存信息,初始化一些系统运行的基本参数。


此时,就可以通过Spring Boot系统启动任务实现,有两种实现方式,分别是ApplicationRunner和CommandLineRunner。


2. ApplicationRunner系统启动任务

定义一个类,实现ApplicationRunner接口,注意该类需要通过@Component注解将其注册为Spring容器管理的组件。


@Component

public class MyApplicationRunner implements ApplicationRunner {

@Override

public void run(ApplicationArguments args) throws Exception {

 System.out.println("系统启动任务MyApplicationRunner");

}

}

当Spring Boot项目启动后,会调用run方法。


3. CommandLineRunner系统启动任务

CommandLineRunner写法和ApplicationRunner基本相同,唯一区别是run方法参数有些不同,代码如下:


@Component

public class MyCommandLineRunner implements CommandLineRunner {

@Override

public void run(String... args) throws Exception {

 System.out.println("系统启动任务MyCommandLineRunner");

}

}

当Spring Boot项目启动后,同样会先会调用run方法。


4. 小结

两种方式没有优劣之分,个人认为ApplicationRunner这个名字更加简洁优雅

版权声明:本文内容转发自阿里云社区,由阿里云实名注册用户自发贡献版权归原作者所有。本站不拥有其著作权,亦不承担相应法律责任。如果您发现本中有涉嫌抄袭的内容,请联系站内客服,本将立刻删除涉嫌侵权内容。 

 

本公司销售:阿里云、腾讯云、百度云、天翼云、金山大米云、金山企业云盘!可签订合同,开具发票。

我有话说: