Computer scienceBackendSpring BootIntroduction to Spring Boot

Console application in Spring Boot

5 minutes read

Creating a console application can be an easier alternative compared to developing full-fledged applications when you want to test, debug, or create a quick proof of concept. CLI apps are efficient, lightweight, and suitable for use in various environments, including servers, embedded systems, and developer tools.

In this topic, we'll dive into the creation of a command-line interface (CLI) application using Spring Boot, discuss its potential use-cases, and learn about the CommandLineRunner interface. So, let's get started!

Creating a CLI application with Spring

Creating a CLI application with Spring Boot is a straightforward process. Spring Boot is flexible and allows us to exclude any components we don't need, such as web, security, or Spring Data, enabling us to focus solely on the console application. To begin, we need to set up a new Spring Boot project. However, instead of using the usual web dependencies, we'll keep it simple and only include the spring-boot-starter dependency. Here's how a basic pom.xml file might look:

<dependencies> 
    <dependency> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter</artifactId> 
    </dependency> 
</dependencies>

Scenarios for a CLI application with Spring

You might be wondering, "When would I need a CLI application in Spring?" Well, CLI applications can be useful in a variety of scenarios. They can be used for automating tasks, running scripts, or even creating utility applications. For instance, you might need to process a large data file and store the results in a database. A CLI application can do this efficiently without the overhead associated with a web interface. Alternatively, you may need a tool to monitor the health of your application and perform some maintenance tasks. A CLI application would be perfect for this job.

Creating a simple CLI app

Let's create a simple CLI application. We'll start by creating a main class for our application. In this class, we'll include a main method that will serve as the entry point. Here's what our basic structure would look like:

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

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

This looks like a typical Spring Boot application, but there's no controller or REST API. Instead, our application will run from the console and exit when it's done.

CommandLineRunner interface

The CommandLineRunner interface is a key player in our CLI application. It's a functional interface within Spring Boot, which means it only contains one method: run(String... args). This method is called just before SpringApplication.run(…) completes. We can use it to execute the logic of our console application.

Let's define a CalculatorService using the @Service annotation to perform a simple addition operation.

import org.springframework.stereotype.Service;

@Service
public class CalculatorService {
    public int sum(int... numbers) {
        int result = 0;
        for (int number : numbers) {
            result += number;
        }
        return result;
    }
}

Now, we can work on our CommandLineRunner bean, which makes use of CalculatorService:

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Scanner;

@SpringBootApplication
public class ConsoleApplication {
    @Autowired
    private CalculatorService calculatorService;

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

    @Bean
    public CommandLineRunner commandLineRunner() {
        return args -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter numbers separated by spaces:");
            String input = scanner.nextLine();
            String[] numbersStr = input.split(" ");
            int[] numbers = new int[numbersStr.length];
            for (int i = 0; i < numbersStr.length; i++) {
                try {
                    numbers[i] = Integer.parseInt(numbersStr[i]);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid number: " + numbersStr[i]);
                }
            }
            int sum = calculatorService.sum(numbers);
            System.out.println("The sum of the numbers is: " + sum);
        };
    }
}

In this example, our CommandLineRunner bean first reads a line of input from the user. It then splits this input into an array of numbers, converts each number into an integer, and finally uses the CalculatorService to calculate the sum of these numbers. It's a real CLI application that interacts with the user and performs a meaningful operation.

Conclusion

And there we have it! We've just created a basic console application using Spring Boot. We've learned that while Spring Boot is widely known for creating web applications, it's also quite capable of running console applications. By understanding when to use a CLI application and how to leverage the CommandLineRunner interface, we've expanded our Spring Boot toolkit and can now create an even more diverse range of applications. Remember, the power of Spring Boot lies in its flexibility and adaptability to meet your specific needs. Happy coding!

25 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo