此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Shell 3.3.3spring-doc.cadn.net.cn

命令注册

定义命令注册是介绍命令结构及其选项的第一步 和参数。这与后面发生的事情松散地解耦,例如解析命令行输入和运行 实际目标代码。从本质上讲,它是向用户显示的命令 API 的定义。spring-doc.cadn.net.cn

命令

命令中的spring-shellstructure 定义为命令数组。这将产生一个 结构,类似于以下示例:spring-doc.cadn.net.cn

command1 sub1
command2 sub1 subsub1
command2 sub2 subsub1
command2 sub2 subsub2
如果定义了子命令,我们目前不支持将命令映射到显式父级。 例如command1 sub1command1 sub1 subsub1不能同时注册。

交互模式

Spring Shell 被设计为在两种模式下工作:交互式(本质上是 是一个REPL其中,您在一系列命令中有一个活动的 shell 实例),并且 非交互式 (命令从命令行逐个执行)。spring-doc.cadn.net.cn

这些模式之间的差异主要在于对可以执行的作的限制 在每种模式下。例如,显示以前的 stacktrace 是不可行的 如果 shell 不再处于活动状态,则命令的命令。通常,shell 是否仍处于活动状态 指示可用信息。spring-doc.cadn.net.cn

此外,处于活跃状态REPLsession 可能会提供有关用户所经历的更多信息 在活动会话中执行。spring-doc.cadn.net.cn

选项

选项可以定义为 long 和 short,其中前缀分别为 和 。 以下示例显示了 long 和 short 选项:---spring-doc.cadn.net.cn

CommandRegistration.builder()
	.withOption()
		.longNames("myopt")
		.and()
	.build();
CommandRegistration.builder()
	.withOption()
		.shortNames('s')
		.and()
	.build();

目标

目标定义命令的执行目标。它可以是 POJO 中的一个方法, 一个ConsumerFunction.spring-doc.cadn.net.cn

方法

使用Method是定义目标的一种方法。 请考虑以下类:spring-doc.cadn.net.cn

public static class CommandPojo {

	String command(String arg) {
		return arg;
	}
}

给定前面清单中显示的现有类,然后你可以注册它的方法:spring-doc.cadn.net.cn

CommandPojo pojo = new CommandPojo();
CommandRegistration.builder()
	.command("command")
	.withTarget()
		.method(pojo, "command")
		.and()
	.withOption()
		.longNames("arg")
		.and()
	.build();

功能

使用Function作为 Target 提供了很大的灵活性来处理 发生在命令执行中,因为您可以使用 一个CommandContextgiven给一个Function.来自Function是 然后是打印到 shell 中的内容。请考虑以下示例:spring-doc.cadn.net.cn

CommandRegistration.builder()
	.command("command")
	.withTarget()
		.function(ctx -> {
			String arg = ctx.getOptionValue("arg");
			return String.format("hi, arg value is '%s'", arg);
		})
		.and()
	.withOption()
		.longNames("arg")
		.and()
	.build();

消费者

使用Consumer与使用Function,区别在于 没有 return 类型。如果你需要将某些东西打印到 shell 中, 您可以获取对Terminal从上下文中打印一些东西 通过它。请考虑以下示例:spring-doc.cadn.net.cn

CommandRegistration.builder()
	.command("command")
	.withTarget()
		.consumer(ctx -> {
			String arg = ctx.getOptionValue("arg");
			ctx.getTerminal().writer()
				.println(String.format("hi, arg value is '%s'", arg));
		})
	.and()
	.withOption()
		.longNames("arg")
		.and()
	.build();

APP信息