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 on how to create a 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 an implementation for the CommandLineRunner interface 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, if 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

In addition to the above implementation declaration, there is another way that you can also define a Bean for the CommandLinerRunner interface.

For example:

The result will be the same as above!

3/5 - (2 votes)

Add Comment