2017-08-10 226 views
2

目前,我試圖使用CommandLineRunner以及ConfigurableApplicationContext作爲默認Web應用程序運行一個彈簧啓動應用程序,並作爲一個獨立的命令行應用程序按需(通過某種類型的命令行參數)運行。當我提供程序參數時,我正在努力找出如何單獨運行這個控制檯應用程序。請任何建議將有所幫助。如何運行彈簧啓動應用程序作爲Web應用程序以及命令行應用程序?

回答

1

CommandLineRunner接口提供,一旦應用程序已啓動拿起命令行參數的有效方法,但它不會有助於改變應用程序的性質。正如您可能已經發現的,應用程序可能不會退出,因爲它認爲它需要處理傳入的Web請求。

您在主要方法中採取的方法對我來說看起來很明智。你需要告訴Spring Boot它不是一個Web應用程序,因此它不應該在啓動後監聽傳入的請求。

我會做這樣的事:

public static void main(String[] args) { 
    SpringApplication application = new SpringApplication(AutoDbServiceApplication.class); 
    application.setWeb(ObjectUtils.isEmpty(args); 
    application.run(args); 
} 

這應該開始在正確的模式應用。然後,您可以像現在一樣使用CommandLineRunner bean。你可能也想看看ApplicationRunner其中有一個稍微好一點的API:

@Component 
public class AutoDbApplicationRunner implements ApplicationRunner { 

    public void run(ApplicationArguments args) { 
     if (ObjectUtils.isEmpty(args.getSourceArgs)) { 
      return; // Regular web application 
     } 
     // Do something with the args. 
     if (args.containsOption(「foo」)) { 
      // … 
     } 
    } 

} 

如果你真的不想AutoDbApplicationRunner豆,甚至可以創建你可以看看在main方法中設置的配置文件,你可以稍後再使用(請參閱SpringApplication.setAdditionalProfiles)。

+0

謝謝菲爾韋伯! –

相關問題