How to create a Spring Boot Remote Shell Command

So today I’ve been looking at the actuator and remote functionality in Spring Boot and thought I’d have a go and getting a custom command working in my simple Spring Boot app.

One challenge from the documentation is it only talks about how to setup the command using Groovy, so what if you are using Java? There are a few pitfalls that catch people out so I thought I’d document them here in one article.

So, the documentation on the remote shell does say that the command will be looked for on the class path at /commands or /crash/commands the subtle point about this is the command should be put in your project so that they are built because the remote shell command are compiled on first use so they need to be in your /resources folder.

So, you should put the source code for any remote shell commands in /src/main/resources/commands/ the downside with this is now that it is in the resources folder the IDE won’t highlight any syntax issues. My tip would be to write the command in your java source tree and then when you are happy with it, drag it into the resources folder. One reason for this is any compilation issues will be ignored when invoking the command.

Dependency required:

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

Two annotations you’ll need on your command are:

@Command

@Usage(“My Test Command”)

These two annotations indicate that this is a shell command and that the command description is “My Test Command”.

The name of your class becomes the command name.

See my example source code below, that was in my Spring Boot Project at /src/main/resources/commands/

 

package commands;
import org.crsh.cli.Command;
import org.crsh.cli.Usage;
import org.crsh.command.BaseCommand;
public class mycommand extends BaseCommand {
    @Command
    @Usage("My Test Command")
    public String main() {
        return "test command invoked";
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s