Java console application with Spring Boot

By default, when we create a Spring Boot project, it will run as a web application with an embedded web container such as Tomcat, Jetty… So in case we want to run the Spring Boot project as a normal Java console, how do we do it? In this tutorial, I will guide you how to create Java application console with your Spring Boot project.

First of all, you also create a normal Spring Boot project using the Spring Tool Suite IDE or the Spring Initializr Web, but note that in the dependencies section, you do not select anything.

My example is as follows:

Java console application with Spring Boot

To run this example as a Java console application, add the implementation interface CommandLineRunner to the main class of the Spring Boot application, in my example SpringBootConsoleApplication class:

This CommandLineRunner interface has a method that we must implement, which is the run() method. This is also the method that allows us to execute code under the console.

For example, now I want to print a message in the console, I will code as follows:

Result:

Java console application with Spring Boot

Let’s say we now have a HelloWorld bean with the following content:

Then, we can use the HelloWorld bean as follows:

Result:

Java console application with Spring Boot

3/5 - (2 votes)

Add Comment