Spring Shell – A Simple Hello World Example

Hello everyone, In this tutorial, we will show you a simple hello world example in spring shell. The following example program has been tested and shared in the post.

Maven Dependency

In order to use or integrate spring shell module as of boot application please make sure you have added following dependencies in your pom.xml file.

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

<dependency>
	<groupId>org.springframework.shell</groupId>
	<artifactId>spring-shell-starter</artifactId>
	<version>2.0.0.RELEASE</version>
</dependency>

Creating a Command using Spring Shell

We can create a cli command using @ShellMethod annotation, but please make sure that the class annotated with @ShellComponent.

package com.dineshkrish;

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

@ShellComponent
public class GreetCommand {

    @ShellMethod("A simple greeting by given name")
    public String greet(final String name) {
        return "Hello "+name;
    }
}

Spring Boot Main Class

package com.dineshkrish;

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

@SpringBootApplication
public class SpringShellApplication {

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

Once all set you can run the main class simply, then you should see the following output.

Output

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-27 17:07:03.555  INFO 50472 --- [           main] c.d.demo.SpringShellApplication          : Starting SpringShellApplication on LAPTOP-RPL08URB with PID 50472 (C:\Users\Dinesh\Desktop\jtrac\jtrac\theamleaf_example\target\classes started by Dinesh in C:\Users\Dinesh\Desktop\jtrac\jtrac\theamleaf_example)
2019-02-27 17:07:03.558  INFO 50472 --- [           main] c.d.demo.SpringShellApplication          : No active profile set, falling back to default profiles: default
2019-02-27 17:07:04.775  WARN 50472 --- [           main] org.jline                                : Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)
2019-02-27 17:07:04.860  INFO 50472 --- [           main] c.d.demo.SpringShellApplication          : Started SpringShellApplication in 1.79 seconds (JVM running for 2.9)

shell:>greet Dinesh
Hello Dinesh
shell:>

References