CommandLineRunner的使用

CommandLineRunner介绍

问题:在项目启动时,我们需要加载或者预先完成某些动作,该怎么办呢?
解决办法:在springBoot中是实现CommandLineRunner接口类
CommandLineRunner翻译过来就是“命令行运行者”,很形象😏

主要有以下方式:

(1)@Component
(2)@SpringBootApplication
(3)声明一个实现了CommandLineRunner接口的Bean

1. @Component实现

具体代码如下:

@SpringBootApplication
public class Demo03Application {

    public static void main(String[] args) {
        System.out.println("step 1: The Service will start");
        SpringApplication.run(Demo03Application.class, args);
        System.out.println("step 5: The Service has started");
    }

}
@Component
@Order(1)
class Runner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("step 3: The Runner1 run...");
    }
}

@Component
@Order(2)
class Runner2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("step 4: The Runner1 run...");
    }
}

运行结果如图所示:

由以上代码可以发现:在SpringApplication.run运行完之后才会运行自己创建的实现类,并且自己的实现类通过@Order()注解控制顺序,数字越小越靠前。
思考一下为什么要加@Component注解呢?

(1)、加入@Component注解后,就可以将对象交给spring管理。
(2)、当Spring 容器初始化完成后, Spring会遍历所有实现CommandLineRunner接口的类, 并运行其run() 方法.

2. @SpringBootApplication实现

具体代码如下:

@SpringBootApplication
public class Demo03Application implements CommandLineRunner{

    public static void main(String[] args) {
        System.out.println("step 1: The Service will start");
        SpringApplication.run(Demo03Application.class, args);
        System.out.println("step 5: The Service has started");
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("app start");
    }
}

运行结果如图所示:

3. @Bean实现

具体代码如下:

@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
 
    @Bean
    public ApplicationStartupRunner schedulerRunner() {
        return new ApplicationStartupRunner();
    }
}
public class ApplicationStartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
    @Override
    public void run(String... args) throws Exception {
        logger.info("Application Started !!");
    }
}

环环无敌大可爱😄

posted @ 2022-04-19 20:33  盐小果  阅读(16505)  评论(0编辑  收藏  举报