如何将 Spring Boot 应用程序同时作为 Web 应用程序和命令行应用程序运行?

Bra*_*hta 9 java eclipse command-line-arguments spring-boot

目前,我正在尝试使用CommandLineRunnerConfigurableApplicationContext来运行 spring boot 应用程序,默认情况下作为 Web 应用程序和按需作为独立的命令行应用程序(通过某种命令行参数)。当提供程序参数时,我正在努力弄清楚如何将它作为控制台应用程序单独运行。请任何建议都会有所帮助。

Gar*_*age 15

我有同样的要求。这就是我能够实现它的方式:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplicationBuilder app = new SpringApplicationBuilder(Application.class);
        if (args.length == 0) { // This can be any condition you want
            app.web(WebApplicationType.SERVLET);
        } else {
            app.web(WebApplicationType.NONE);
        }
        app.run(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个控制台应用程序运行器。

@Component
@ConditionalOnNotWebApplication
public class ConsoleApplication implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("************************** CONSOLE APP *********************************");
    }
}
Run Code Online (Sandbox Code Playgroud)

当您构建您的应用程序时bootJar,您可以使用 来将应用程序作为 Web 应用程序运行 java -jar app.jar,并使用 来作为命令行应用程序运行java -jar app.jar anything #based on the condition you specified

希望这可以帮助。

编辑:

实现此目的的更好方法是将 Application.java 更改为如下所示,并保留 ConsoleApplication.java 如上所示。

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后运行您的bootJarwithjava -jar -Dspring.main.web-application-type=NONE app.jar会将应用程序作为控制台应用程序运行。并且不通过任何spring.main.web-application-type将作为网络应用程序运行。


Phi*_*ebb 6

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);
}
Run Code Online (Sandbox Code Playgroud)

这应该以正确的模式启动应用程序。然后,您可以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”)) {
            // …
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您真的不想AutoDbApplicationRunner创建 bean,您可以查看在 main 方法中设置一个配置文件,以便稍后使用(请参阅 参考资料SpringApplication.setAdditionalProfiles)。