SpringBoot如何启动就执行本身定义的逻辑?

在实际项目开发中,咱们可能会但愿在项目启动后去加载一些资源信息、执行某段特定逻辑等等初始化工做,这时候咱们就须要用到SpringBoot提供的开机自启的功能,SpringBoot给咱们提供了两个方式:CommandLineRunnerApplicationRunnerCommandLineRunnerApplicationRunner接口是在容器启动成功后的最后一步回调,这两种方法提供的目的是为了知足,在项目启动的时候马上执行某些方法java

接下来给你们讲解一下这两个方式如何使用数组

1、CommandLineRunner

一、建立SpringBoot项目

如何建立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

  • 监听类1
/** * @author Gjing */
@Component
@Order(1)
public class MyStartRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("本身定义的第一个启动后事件开始执行。。。。。。。");
    }
}
复制代码
  • 监听类2
/** * @author Gjing **/
@Component
@Order(2)
public class MyStartRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("本身定义的第二个启动后事件开始执行。。。。。。。");
    }
}
复制代码

启动项目orm


2、ApplicationRunner

建立自定义监听类cdn

实现ApplicationRunner接口blog

/** * @author Gjing **/
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("我自定义的ApplicationRunner事件。。。。。。");
    }
}
复制代码

启动项目接口


3、二者的区别

ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口

以上图片内容免费领取传送门:shimo.im/docs/BYMjlk…

相关文章
相关标签/搜索