在实际项目开发中,咱们可能会但愿在项目启动后去加载一些资源信息、执行某段特定逻辑等等初始化工做,这时候咱们就须要用到SpringBoot提供的开机自启
的功能,SpringBoot给咱们提供了两个方式:CommandLineRunner
和ApplicationRunner
,CommandLineRunner
、ApplicationRunner
接口是在容器启动成功后的最后一步回调,这两种方法提供的目的是为了知足,在项目启动的时候马上执行某些方法java
接下来给你们讲解一下这两个方式如何使用数组
如何建立SpringBoot项目这里不作过多介绍ide
实现CommandLineRunner接口spa
/** * @author Gjing **/
@Component
public class MyStartRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("本身定义的第一个启动后事件开始执行。。。。。。。");
}
}
复制代码
启动项目
命令行
若是须要多个监听类,咱们只须要定义多个就好了,经过@Order注解或者实现Order接口来标明加载顺序code
/** * @author Gjing */
@Component
@Order(1)
public class MyStartRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("本身定义的第一个启动后事件开始执行。。。。。。。");
}
}
复制代码
/** * @author Gjing **/
@Component
@Order(2)
public class MyStartRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("本身定义的第二个启动后事件开始执行。。。。。。。");
}
}
复制代码
启动项目orm
建立自定义监听类cdn
实现ApplicationRunner接口blog
/** * @author Gjing **/
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("我自定义的ApplicationRunner事件。。。。。。");
}
}
复制代码
启动项目接口
ApplicationRunner
中run方法的参数为ApplicationArguments
,而CommandLineRunner
接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner
接口
以上图片内容免费领取传送门:shimo.im/docs/BYMjlk…