Spring Boot Shell

Spring Boot Shell allows you to create interactive command-line applications using Spring Boot. It’s ideal for building CLI tools.

Here’s a complete example:


1️⃣ Add Dependencies

In your pom.xml (for Maven):

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.shell</groupId>
        <artifactId>spring-shell-starter</artifactId>
        <version>3.1.2</version> <!-- Use latest -->
    </dependency>
</dependencies>

Or with Gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.shell:spring-shell-starter:3.1.2'
}

2️⃣ Create a Spring Boot Application

package com.example.shellapp;

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

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

3️⃣ Create a Shell Component

package com.example.shellapp.commands;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellComponent
public class MyCommands {

    @ShellMethod("Say hello to someone")
    public String hello(@ShellOption(defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }

    @ShellMethod("Add two numbers")
    public int add(int a, int b) {
        return a + b;
    }
}

4️⃣ Run the Application

Run your Spring Boot app as usual (mvn spring-boot:run or from your IDE).
You will see a shell prompt like:

shell:>

You can now type commands:

shell:>hello
Hello, World!
shell:>hello Alice
Hello, Alice!
shell:>add 5 7
12

Key Points:

  • @ShellComponent marks a class as containing shell commands.
  • @ShellMethod marks a method as a CLI command.
  • @ShellOption allows default values or optional arguments.
  • You can create complex commands, inject services, and even handle subcommands.

Leave a Reply