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 @   每月工资一万八  阅读(134)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示