|
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Shell 4.0.1! |
Organizing Commands
When your shell starts to provide a lot of functionality, you may end up
with a lot of commands, which could be confusing for your users. By typing help,
they would see a daunting list of commands, organized in alphabetical order,
which may not always be the best way to show the available commands.
To alleviate this possible confusion, Spring Shell provides the ability to group commands together,
with reasonable defaults. Related commands would then end up in the same group (for example, User Management Commands)
and be displayed together in the help screen and other places.
Commands can be grouped by specifying a group attribute in the @Command annotation:
@Command(name = "example", group = "My Commands")
public String example() {
return "Hello";
}
The group can also be specified programmatically when using the programmatic registration model
using the Command.Builder.group(String) method:
@Bean
Command myCommand() {
return Command.builder()
.name("mycommand")
.group("My Commands")
.execute(context -> {
System.out.println("This is my command!");
});
}
Typically, related commands are defined in the same class (to easily share state between commands), and the group name and prefix are specified at the class level, which means that all commands defined in that class will belong to the same group. Here is an example of how to do that:
@CommandGroup(name = "Authentication Commands", prefix = "auth")
public class AuthenticationCommands {
private boolean authenticated = false;
@Command(name = "login", description = "Log in to the system")
public void login() {
// Authentication logic here
authenticated = true;
System.out.println("Logged in successfully!");
}
@Command(name = "logout", description = "Log out of the system")
public void logout() {
// Logout logic here
authenticated = false;
System.out.println("Logged out successfully!");
}
}
In this example, both the login and logout commands belong to the Authentication Commands group, and they will be displayed together in the help screen under that group. The prefix attribute specifies a common prefix for all commands in that group, which can be used to invoke the commands (e.g., auth login and auth logout).
If a command provides a group attribute, it will take precedence over the group specified at the class level. This allows you to override the group for specific commands if needed.
|