Spring Boot命令行運行器

CommandLineRunner是一個帶有run方法的簡單spring引導接口。Spring Boot啓動後將自動調用實現CommandLineRunner接口的所有bean的run方法。

Command Line Runner在加載應用程序上下文之後以及Spring Application run方法完成之前執行,相當於你的應用的初始化過程,一般用來實現一些數據預先加載或預先處理。

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    private final Logger logger = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
     ....
    }

}

上面的run方法參數是命令行參數,使用java -jar 啓動這個應用的命令行參數。 如果有多個命令行運行器,可以進行排序:

@Component
@Order(1)
public class AnotherDatabaseLoader implements CommandLineRunner {

@Component
@Order(2)
public class DataLoader implements CommandLineRunner {

另外一種在主應用的寫法:

@SpringBootApplication
public class UnsplashApplication {

    public static void main(String args) {
        SpringApplication.run(UnsplashApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(){
        return args -> {
            System.out.println("CommandLineRunner running in the UnsplashApplication class...");
        };
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章