溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot命令行運(yùn)行器的實(shí)現(xiàn)方法

發(fā)布時(shí)間:2020-08-21 06:09:48 來(lái)源:腳本之家 閱讀:211 作者:banq 欄目:編程語(yǔ)言

CommandLineRunner是一個(gè)帶有run方法的簡(jiǎn)單spring引導(dǎo)接口。Spring Boot啟動(dòng)后將自動(dòng)調(diào)用實(shí)現(xiàn)CommandLineRunner接口的所有bean的run方法。

Command Line Runner在加載應(yīng)用程序上下文之后以及Spring Application run方法完成之前執(zhí)行,相當(dāng)于你的應(yīng)用的初始化過程,一般用來(lái)實(shí)現(xiàn)一些數(shù)據(jù)預(yù)先加載或預(yù)先處理。

@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方法參數(shù)是命令行參數(shù),使用java -jar 啟動(dòng)這個(gè)應(yīng)用的命令行參數(shù)。

如果有多個(gè)命令行運(yùn)行器,可以進(jìn)行排序:

@Component
@Order(1)
<b>public</b> <b>class</b> AnotherDatabaseLoader implements CommandLineRunner {

@Component
@Order(2)
<b>public</b> <b>class</b> DataLoader implements CommandLineRunner {

另外一種在主應(yīng)用的寫法:

@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>

總結(jié)

以上所述是小編給大家介紹的Spring Boot命令行運(yùn)行器的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI