How to run spring boot application both as a web application as well as a command line application?

Viewed 4598

Currently, I am trying to use the CommandLineRunner along with the ConfigurableApplicationContext to run a spring boot application both as a web application by default and as a standalone command line application on demand (via command line parameters of some sort). I am struggling figuring out how to solely run this as a console application when program arguments are supplied. Please any suggestions would help.

2 Answers

I had the same requirement. This is how I was able to achieve it:

@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);
    }
}

And this is a console application runner.

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

When you build your bootJar, you can run application as Web app using java -jar app.jar and as a command line app using java -jar app.jar anything #based on the condition you specified.

Hope this helps.

EDIT:

A better way to achieve this is changing Application.java as following and keeping ConsoleApplication.java as shown above.

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

and then running your bootJar with java -jar -Dspring.main.web-application-type=NONE app.jar will run the application as console application. And not passing any spring.main.web-application-type will run as a web application.

Related