本文来说下CommandLineRunner和ApplicationRunner的使用
文章目录
- ApplicationRunner
- 使用示例
- 程序结果
- CommandLineRunner
- 使用示例
- 程序结果
- ApplicationListener
- 触发时机
- 使用实例
- 程序结果
- 注意问题
ApplicationRunner
使用起来很简单,只需要实现CommandLineRunner或者ApplicationRunner接口,重写run方法就行。在springboot完全初始化完毕后,会执行CommandLineRunner和ApplicationRunner,两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数
使用示例
代码实例
package com.wideth.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;/**** 在springboot完全初始化完毕后,* 会执行CommandLineRunner和ApplicationRunner,* 两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数。*/
@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args){log.info("====>>> MyApplicationRunner.run()正在执行=========");}
}
程序结果
程序结果
CommandLineRunner
使用示例
代码实例
package com.wideth.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;/**** 在springboot完全初始化完毕后,* 会执行CommandLineRunner和ApplicationRunner,* 两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数。*/
@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args){log.info("====>>> MyCommandLineRunner.run()正在执行=========");}
}
程序结果
程序结果
ApplicationListener
通过事件监听我们也可以实现springboot启动执行方法。实现ApplicationListener,重写onApplicationEvent方法,便可在所有的bean加载完毕后执行。
触发时机
在IOC的容器的启动过程,当所有的bean都已经处理完成之后,spring ioc容器会有一个发布ContextRefreshedEvent事件的动作。
使用实例
使用实例
package com.wideth.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;/**** 在IOC的容器的启动过程,* 当所有的bean都已经处理完成之后,* spring ioc容器会有一个发布* ContextRefreshedEvent事件的动作。*/
@Slf4j
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {@Overridepublic void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {log.info("====>>> MyApplicationListener.onApplicationEvent()正在执行=========");}
}
程序结果
程序结果
注意问题
系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)
这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理
//root application context 没有parentif (event.getApplicationContext().getParent() == null) { //逻辑代码}