Spring Boot Shell : CLI app to execute your commands

Spring Boot Shell : CLI app to execute your commands

A CLI command line program which take string argument from keyboard and executes the program based on input, Assume you are write an migration tool you have to copy contents of your folder to another, or you have remove temp files, convert one file format to another, or resize the image or execute CURL request, or show some cool party trick to print some console out put to pretend to be hacker,its simple all you need is Spring Shell component to these, in this article i will not show these use cases,but instead will help getting started Spring Shell, while i was developing spring scheduler application wanted to check the logic of some corn task before deploying to production instance or wanted to manually execute those function spring shell came in handy. so now we shall begin Getting started with spring shell

Lets Begin Creating Adding the dependency.

<dependencies>
    <dependency>
        <groupId>org.springframework.shell</groupId>
        <artifactId>spring-shell-starter</artifactId>
        <version>2.0.1.BUILD-SNAPSHOT</version>
    </dependency>
</dependencies>

And also add the repository to pull the dependency.

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/libs-snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

   So we shall begin writing CLI commands, will take up some dummy example where when you type date will print the date some thing like that. as to keep the tutorial simple and stupid.

@ShellComponent
public class SampleCommands {

    @ShellMethod("hello")
    public String SayHello() {
      System.out.println("Hi")
    }
    
}

Also you can provide argument to the the command  as input by using annotation @ShellOption

Sample method will look like

@ShellComponent
public class SampleCommands {

    @ShellMethod("hello")
    public String greet( @ShellOption(mandatory = true) String name) {
      System.out.println("Hi" + name)
    }
    
}

So the input time could be of any object like String,Long,Local etc base on the declared type boxing and un-boxing is handled by spring internally.