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 annotate the methods with@Command. -
In the programmatic model, you use a lower-level approach, defining commands as beans.
With the annotation model, the class containing command definitions should not be excluded from component scanning, otherwise the commands will not be registered. This is a common mistake when using @ComponentScan with excludeFilters and excluding the package containing command classes.
|
Annotation-Based Registration
The @Command annotation marks a method as a candidate for command registration.
In the following example, a command example is defined.
@Component
class MyCommands {
@Command(name = "example")
public String example() {
return "Hello";
}
}
| The command name is optional. If it is not provided, the method name is used. When the command returns a value, it will be printed to the shell output. |
Outside a Spring Boot application, use @EnableCommand on a configuration class
to register the classes containing your @Command methods.
@EnableCommand({ MyCommands.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 class 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.