CommandLineRunner

CommandLineRunner的使用 - 盐小果 - 博客园 (cnblogs.com)

 

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

 

@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 @ 2023-02-16 17:00  每月工资一万八  阅读(142)  评论(0)    收藏  举报