方式一:实现CommandLineRunner接口
1、定义
CommandLineRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。
可以通过@Order注解(属性指定数字越小表示优先级越高)或者Ordered接口来控制执行顺序。
2、使用
实现CommandLineRunner接口 然后在run方法里面调用需要调用的方法即可,好处是方法执行时,项目已经初始化完毕,是可以正常提供服务的。同时该方法也可以接受参数,可以根据项目启动时: java -jar xxx.jar arg1 arg2 arg3 传入的参数进行一些处理。
@Component
@Order(value = 1)
public class StartRunnerOne implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>服务启动第一个开始执行的任务<<<<");
}
}
@Component
@Order(value = 2)
public class StartupRunnerTwo implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>服务第二顺序启动执行<<<<");
}
}
方式二:实现ApplicationRunner接口
1、定义
ApplicationRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。
实现ApplicationRunner接口和实现CommandLineRunner接口基本是一样的,唯一的不同是启动时传参的格式,CommandLineRunner对于参数格式没有任何限制,更加松散一些,ApplicationRunner接口参数格式必须是:–key=value。
可以通过@Order注解(属性指定数字越小表示优先级越高)或者Ordered接口来控制执行顺序。
2、使用
@Component //此类一定要交给spring管理
public class ConsumerRunner implements ApplicationRunner{
@Override
public void run(ApplicationArgumers args) throws Exception{
//代码
System.out.println("需要在springBoot项目启动时执行的代码---");
}
}
方式三:实现ApplicationListener接口
1、定义
实现接口ApplicationListener方式和实现ApplicationRunner,CommandLineRunner接口都不影响服务,都可以正常提供服务,注意监听的事件,通常是ApplicationStartedEvent 或者ApplicationReadyEvent,其他的事件可能无法注入bean。
2、使用
@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("listener");
}
}
三种方式的执行顺序如何?
如果监听的是ApplicationStartedEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之前执行。
如果监听的是ApplicationReadyEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之后执行。
CommandLineRunner和ApplicationRunner 默认是ApplicationRunner先执行,如果双方指定了@Order 则按照@Order的大小顺序执行,数字越小优先级越高。
本文介绍SpringBoot中通过实现CommandLineRunner、ApplicationRunner及ApplicationListener接口来执行启动任务的方法,并阐述了它们之间的执行顺序。
2129

被折叠的 条评论
为什么被折叠?



