命令语法

选项和参数

命令选项和参数可以通过方法参数来定义:spring-doc.cadn.net.cn

class Example2 {

	@Command(name = "hi", description = "Say hi to a given name", group = "greetings",
			help = "A command that greets the user with 'Hi ${name}!' with a configurable suffix. Example usage: hi -s=! John")
	public void sayHi(
			@Argument(index = 0, description = "the name of the person to greet",
					defaultValue = "world") String name,
			@Option(shortName = 's', longName = "suffix", description = "the suffix of the greeting message",
					defaultValue = "!") String suffix) {
		System.out.println("Hi " + name + suffix);
	}

}

选项使用@Option注解定义,而参数使用@Argument注解定义。 选项具有名称,而参数是位置性的。选项可以有简短的名称(单字符)和长名称(多字符)。spring-doc.cadn.net.cn

选项可以通过添加验证注解到方法参数中,使用Bean Validation API进行验证。更多详细信息请参阅验证命令选项部分。spring-doc.cadn.net.cn

解析规则

Spring Shell 遵循与 Spring Boot 相同的解析规则,但提供了遵循 POSIX 样式的增强功能。 选项可以在长形式 --key=value--key value 以及短形式 -k=value-k value 中指定。 选项和参数可以以任意顺序指定。参数在其他参数中的索引是基于 0 的:spring-doc.cadn.net.cn

CommandSyntax  ::= CommandName [SubCommandName]* [Option | Argument]*
CommandName    ::= String
SubCommandName ::= String
Option         ::= ShortOption | LongOption
ShortOption    ::= '-' Char ['='|' ']? String
LongOption     ::= '--' String ['='|' ']? String
Argument       ::= String
$>mycommand mysubcommand --optionA=value1 arg1 -b=value2 arg2 --optionC value3 -d value4
当指定了一个选项时,总是期望为该选项提供一个值,即使它是布尔类型的也是如此。这是为了能够区分选项值和参数。此外,短选项不能组合(例如,-abc 不被支持)。
要避免歧义,优先使用命名选项而不是位置参数,尤其是在涉及子命令的情况下(详见命令行接口指南)。

自定义解析规则

Spring Shell 4 提供了一种新的 API,称为 CommandParser,允许您自定义命令解析规则。 如果默认的解析规则不符合您的需求,您可以通过实现CommandParser接口来编写自己的解析器。 一旦自定义解析器实现完毕,就可以将其注册为应用上下文中的一个 Bean,Spring Shell 将使用它进行命令解析。spring-doc.cadn.net.cn