Command Registration
There are two different ways to define a command, through an annotation model and through a programmatic model:
-
In the annotation model, you define your methods in a
@Componentclass and the methods with specific annotations. -
In the programmatic model, you use a more low level approach, defining commands as beans.
Annotation-Based Registration
The @Command annotation marks a method as a candidate for command registration.
In below example a command example is defined.
class Example1 {
@Command(name = "example")
public String example() {
return "Hello";
}
}
| The command name optional, if not provided the method name will be used as command name. When the command returns a value, it will be printed to the shell output. |
Using a @Command will not automatically register command targets, instead it is required to use
@EnableCommand annotations. This model is familiar from other parts of Spring umbrella and
provides better flexibility for a user being inclusive rather than exclusive for command targets.
You can define target classes using @EnableCommand. It will get picked from all Configuration
classes.
@EnableCommand({ Example1.class, Example2.class })
class App {
}
@EnableCommand is not required in a Spring Boot application, as Spring Boot auto-configuration
will take care of that.
|
Programmatic Registration
In the programmatic model, commands can be defined as beans of type Command:
@Bean
Command myCommand() {
return Command.builder().name("mycommand").execute(context -> {
context.outputWriter().println("This is my command!");
});
}
You can also use the AbstractCommand class to simplify command definitions:
@Bean
Command myCommand() {
return new AbstractCommand("mycommand", "This is my command") {
@Override
public ExitStatus doExecute(CommandContext commandContext) {
println("This is my command!", commandContext);
return ExitStatus.OK;
}
};
}
AbstractCommand provides some utility methods to simplify command creation like
handling help options (-h and --help) and printing messages to the shell output.
Command Registry
The CommandRegistry interface holds the set of commands known to the Shell application.
It is possible to dynamically register and unregister commands.
By default, Spring Shell will populate the CommandRegistry with commands defined in the
application context.