CommandLineRunner是一個帶有run方法的簡單spring引導接口。Spring Boot啟動后將自動調用實現CommandLineRunner接口的所有bean的run方法。
Command Line Runner在加載應用程序上下文之后以及Spring Application run方法完成之前執行,相當于你的應用的初始化過程,一般用來實現一些數據預先加載或預先處理。
@SpringBootApplication<b>public</b> <b>class</b> DemoApplication implements CommandLineRunner { <b>private</b> <b>final</b> Logger logger = LoggerFactory.getLogger(DemoApplication.<b>class</b>); <b>public</b> <b>static</b> <b>void</b> main(String args) { SpringApplication.run(DemoApplication.<b>class</b>, args); } @Override <b>public</b> <b>void</b> run(String... strings) throws Exception { .... }}
上面的run方法參數是命令行參數,使用java -jar 啟動這個應用的命令行參數。
如果有多個命令行運行器,可以進行排序:
@Component@Order(1)<b>public</b> <b>class</b> AnotherDatabaseLoader implements CommandLineRunner {@Component@Order(2)<b>public</b> <b>class</b> DataLoader implements CommandLineRunner {
另外一種在主應用的寫法:
@SpringBootApplication<b>public</b> <b>class</b> UnsplashApplication { <b>public</b> <b>static</b> <b>void</b> main(String args) { SpringApplication.run(UnsplashApplication.<b>class</b>, args); } @Bean CommandLineRunner runner(){ <b>return</b> args -> { System.out.println(<font>"CommandLineRunner running in the UnsplashApplication class..."</font><font>); }; }}</font>
總結
以上所述是小編給大家介紹的Spring Boot命令行運行器的實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
|
新聞熱點
疑難解答
圖片精選