Spring Series - Interactive Application with the Spring Shell
Introduction
Spring Shell is a side project which allows you to write interactive shell applications. To work with this, you need to add the following dependency manually to the pom.xml
file(For this I am creating a new project named demo with the same configurations I have explained here).
<properties>
...
<spring-shell.version>3.1.3</spring-shell.version>
</properties>
...
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell-starter</artifactId>
<version>${spring-shell.version}</version>
</dependency>
Interactive Application
If you start the Spring Boot application, the mere existence of this dependency makes the shell to be started with shell:>
The shell comes with integrated commands, which can be viewed by using the help
command.
Write Shell Component
We can register new commands with the shell. The commands are set in classes annotated with @ShellComponent
. Let’s create a new file in demo
package to show our name whenever we run it.
package com.example.demo.demo;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
@ShellComponent
public class DemoComponent {
@ShellMethod("Display name")
public String userName(){
return "Nipuna";
}
}
When we create a @ShellComponent
the outside users can call the methods inside it. There are three requirements for this.
Name → A shell method has a very specific name because this is automatically converted to the shell command. The method
userName()
will be available asuser-name
in the shell.@ShellMethod
→This method gives us an idea about what specific methods do.Documentation → A shell method gets documentation, which is displayed later with
help
command.Shell Methods with Parameters
Shell methods also can accept values from the outside. For instance, if we want a shell method that reverses a given text and makes it lowercase, we can implement it as shown below.
@ShellMethod("Converts the string to lowercase and reversible") public String lowerReversible(String input){ StringBuilder sb = new StringBuilder(input); sb.reverse(); return sb.toString().toLowerCase(); }
Configurations
Furthermore, we can use configuration properties to further change the Spring Shell’s behavior.
spring.shell.interactive.enabled
→ If set tofalse
the Spring Shell won’t start.spring.shell.history.enabled
→ By default, Spring Shell writes all entered commands to a log file. If it is set tofalse
the file isn’t written.spring.shell.history.name
→ The name of the log file can be set via this. If it’s not set,spring.application.name
is evaluated.
So this is it regarding, Interactive Application with the Spring Shell. In the next article, we will look at Dependency Injection.