项目启动后,执行run方法中的代码。

如下所示:

package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
  }
}

 

二、如果有多个类实现CommandLineRunner接口,如何保证顺序

使用@Order 注解,通过源码查看,order的值越小优先级越高

如下所示:

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服务启动执行 2222 <<<<<<<<<<<<<");
    }
}    

 

三、CommandLineRunner接口在SpringBoot启动时执行的顺序

CommandLineRunner接口的run()方法会在spring bean初始化之后,SpringApplication run之前执行,可以控制在项目启动前初始化资源文件,比如初始化线程池,提前加载好加密证书等
 

四、Springboot中的类似接口

ApplicationRunner

 
 

相关文章:

  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-07
  • 2022-12-23
  • 2021-10-04
  • 2021-09-04
  • 2021-07-19
  • 2021-09-04
相关资源
相似解决方案