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 !!");
    }
}

環環無敵大可愛😄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM