|
此版本仍在开发中,尚未被认为是稳定版。请使用最新稳定版 Spring Shell 4.0.1! |
命令注册
有定义命令的两种不同方式,通过注解模型和程序化模型:
-
在注解模型中,您在一个
@Component类中定义方法,并使用特定的注解来标记这些方法。 -
在程序化模型中,您会采用更底层的方法,将命令定义为bean。
注解基础注册
注解 @Command 将一个方法标记为命令注册的候选者。 在下面的示例中,定义了一个命令 example。
class Example1 {
@Command(name = "example")
public String example() {
return "Hello";
}
}
| 命令名称是可选的,如果未提供,将使用方法名称作为命令名称。 当命令返回一个值时,它将被打印到 shell 输出中。 |
使用 @Command 将不会自动注册命令目标,而是需要使用 @EnableCommand 注解。这种模式来自 Spring 轮廓的其他部分,并为用户提供了更好的灵活性,使其更加包容而不是排斥命令目标。
您可以使用@EnableCommand定义目标类。它将从所有的配置类中被识别。
@EnableCommand({ Example1.class, Example2.class })
class App {
}
@EnableCommand 是一个 Spring Boot 应用程序不需要的元素,因为 Spring Boot 的自动配置
会处理这个问题。 |
程序化注册
在程序化模型中,命令可以定义为类型Command的bean:
@Bean
Command myCommand() {
return Command.builder().name("mycommand").execute(context -> {
context.outputWriter().println("This is my command!");
});
}
您可以使用AbstractCommand类来简化命令定义:
@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 提供了一些实用方法来简化命令创建,例如处理帮助选项(-h 和 --help)以及将消息输出到控制台。
Command Registry
The CommandRegistry接口包含Shell应用程序已知的所有命令集。
可以动态注册和注销命令。
默认情况下,Spring Shell 会将 CommandRegistry 填充为应用程序上下文中定义的命令。