2017-08-10 268 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

谢谢菲尔韦伯! –

相关问题