我們在開發中可能會有這樣的情景。需要在容器啓動的時候執行一些內容。比如讀取配置文件,數據庫連接之類的。SpringBoot給我們提供了兩個接口來幫助我們實現這種需求。這兩個接口分別爲CommandLineRunner和ApplicationRunner。他們的執行時機爲容器啓動完成的時候。
這兩個接口中有一個run方法,我們只需要實現這個方法即可。這兩個接口的不同之處在於:ApplicationRunner中run方法的參數爲ApplicationArguments,而CommandLineRunner接口中run方法的參數爲String數組。下面我寫兩個簡單的例子,來看一下這兩個接口的實現。
CommandLineRunner
- package com.zkn.learnspringboot.runner;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.stereotype.Component;
- /**
- * Created by zkn on 2016/8/12.
- */
- @Component
- public class TestImplCommandLineRunner implements CommandLineRunner {
- @Override
- public void run(String... args) throws Exception {
- System.out.println("<<<<<<<<<<<<這個是測試CommandLineRunn接口>>>>>>>>>>>>>>");
- }
- }
ApplicationRunner接口
- package com.zkn.learnspringboot.runner;
- import org.springframework.boot.ApplicationArguments;
- import org.springframework.boot.ApplicationRunner;
- import org.springframework.stereotype.Component;
- /**
- * Created by zkn on 2016/8/12.
- * 注意:一定要有@Component這個註解。要不然SpringBoot掃描不到這個類,是不會執行。
- */
- @Component
- public class TestImplApplicationRunner implements ApplicationRunner {
- @Override
- public void run(ApplicationArguments args) throws Exception {
- System.out.println(args);
- System.out.println("這個是測試ApplicationRunner接口");
- }
- }