命名

如果需要修改选项的长名称,可以使用 OptionNameModifier 接口,它是一个简单的 Function<String, String>。在这个接口中,原始选项名称作为输入,修改后的名称作为输出。

修改器可以根据 CommandRegistration 中的 OptionSpec 定义,也可以作为 Bean 或通过配置属性全局默认。在 OptionSpec 中手动定义的修改器优先于全局定义的修改器。默认情况下没有定义全局修改器。

你可以在 CommandRegistration 中为选项定义一个。

CommandRegistration.builder()
	.withOption()
		.longNames("arg1")
		.nameModifier(name -> "x" + name)
		.and()
	.build();

添加一个类型为 OptionNameModifier单例 Bean,它将成为全局默认值。

@Bean
OptionNameModifier sampleOptionNameModifier() {
	return name -> "x" + name;
}

也可以通过配置属性 spring.shell.option.naming.case-type 来添加,它会根据定义的类型自动配置一个。

noop 表示不进行任何操作,camelsnakekebabpascal 分别激活内置的 camelCasesnake_casekebab-casePascalCase 修改器。

如果直接创建 CommandRegistration bean,通过配置属性实现的全局默认值仅在使用预配置的 Builder 实例时才有效。详见 [使用 Shell 命令的编程模型]
spring:
  shell:
     option:
       naming:
         case-type: noop
         # case-type: camel
         # case-type: snake
         # case-type: kebab
         # case-type: pascal

例如,在带注解的方法中定义的选项如下。

@ShellMethod(key = "option-naming-sample")
public void optionNamingSample(
	@ShellOption("from_snake") String snake,
	@ShellOption("fromCamel") String camel,
	@ShellOption("from-kebab") String kebab,
	@ShellOption("FromPascal") String pascal
) {}

默认情况下,该命令的 help 会显示直接来自 @ShellOption 的名称。

OPTIONS
       --from_snake String
       [Mandatory]

       --fromCamel String
       [Mandatory]

       --from-kebab String
       [Mandatory]

       --FromPascal String
       [Mandatory]

定义 spring.shell.option.naming.case-type=kebab,将添加默认修改器,选项名称将变为如下所示。

OPTIONS
       --from-snake String
       [Mandatory]

       --from-camel String
       [Mandatory]

       --from-kebab String
       [Mandatory]

       --from-pascal String
       [Mandatory]
© . This site is unofficial and not affiliated with VMware.