命名

如果需要修改選項的長名稱,可以使用 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.