资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringBoot如何初始化运行特定方法

这篇文章主要介绍了Spring Boot如何初始化运行特定方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

创新互联从2013年开始,是专业互联网技术服务公司,拥有项目网站制作、成都网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元阿里地区做网站,已为上家服务,为阿里地区各地企业和个人服务,联系电话:13518219792

Spring Boot提供了两种 “开机自启动” 的方式,ApplicationRunner和CommandLineRunner

这两种方式的目的是为了满足,在容器启动时like执行某些方法。我们可以通过实现ApplicationRunner或者CommandLineRunner来实现,他们都是在SpringAppliaction执行之后开始执行的。这个特性可以让我们自定义一些在容器启动时需要初始化的逻辑

ApplicationRunner接口:

官方doc:

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Ordered

当该接口包含在SpringApplication中时执行。多个ApplicationRunner通过Order直接进行排序:

/**
 * 初始化类
 */
@Order(1) // @Order注解可以改变执行顺序,越小越先执行
@Component
public class MyApplicationRunner1 implements ApplicationRunner {
  /**
   * 会在服务启动完成后立即执行
   */
  @Override
  public void run(ApplicationArguments arg0) throws Exception {
    System.out.println("MyApplicationRunner1----" + arg0);
  }
}
/**
 * 初始化类
 */
@Order(2) 
@Component
public class MyApplicationRunner2 implements ApplicationRunner {
  /**
   * 会在服务启动完成后立即执行
   */
  @Override
  public void run(ApplicationArguments arg0) throws Exception {
    System.out.println("MyApplicationRunner2----" + arg0);
  }
}

容器启动后的运行结果:

Spring Boot如何初始化运行特定方法

可以看到多个ApplicationRunner执行顺序是按照Order中的值执行的,并且每个的入参都是同一个ApplicationArguments实例(具体原因后面分析)

CommandLineRunner接口:

二者的官方doc基本一样,区别在于接收的参数不一样

/**
 * 初始化类
 */
@Order(1) // @Order注解可以改变执行顺序,越小越先执行
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {
  /**
   * 会在服务启动完成后立即执行
   */
  @Override
  public void run(String... args) throws Exception {
    System.out.println("MyCommandLineRunner1----" + args);
  }
}
/**
 * 初始化类
 */
@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {
  /**
   * 会在服务启动完成后立即执行
   */
  @Override
  public void run(String... args) throws Exception {
    System.out.println("MyCommandLineRunner2----" + args);
  }
}

容器启动后的运行结果:

Spring Boot如何初始化运行特定方法

可以看到多个CommandLineRunner的执行效果跟ApplicationRunner一模一样

最后看下源码:

SpringApplication启动时,会执行其run方法中的afterRefresh方法:

Spring Boot如何初始化运行特定方法

在afterRefresh中可以看到这两个接口被执行,并且每个ApplicationRunner或CommandLineRunner实例都是用的同一个入参:

Spring Boot如何初始化运行特定方法

感谢你能够认真阅读完这篇文章,希望小编分享的“Spring Boot如何初始化运行特定方法”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!


本文名称:SpringBoot如何初始化运行特定方法
网页链接:http://cdkjz.cn/article/jsopio.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220