Spring Boot非Web項目運行的方法 轉載
-
有時候一些項目並不需要提供 Web 服務,例如跑定時任務的項目,如果都按照 Web 項目啓動未免畫蛇添足浪費資源
-
爲了達到非 Web 運行的效果,首先調整 Maven 依賴,不再依賴 spring-boot-starter-web,轉而依賴最基礎的 spring-boot-starter:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
- 此時按照原先的方式啓動 SpringBootApplication 會發現啓動加載完之後會立即退出,這時需要做點工作讓主線程阻塞讓程序不退出:
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Thread.currentThread().join();
}
}
- 這裏利用了 SpringBoot 提供的 CommandLineRunner 特性,這個名字比較有欺騙性,實際效果如下
- SpringBoot 應用程序在啓動後,會遍歷 CommandLineRunner 接口的實例並運行它們的 run 方法。也可以利用 @Order 註解(或者實現Order接口)來規定所有 CommandLineRunner 實例的運行順序
很棒,寫一點小工具就很nice