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.