コマンド登録

コマンドを定義するには、アノテーションモデルを使用する方法とプログラムモデルを使用する方法の 2 つがあります。

  • In the annotation model, you define your methods in a @Component class and annotate the methods with @Command.

  • In the programmatic model, you use a lower-level approach, defining commands as beans.

アノテーションモデルを使用する場合、コマンド定義を含むクラスをコンポーネントスキャンから除外してはいけません。除外してしまうと、コマンドが登録されません。これは、@ComponentScan と excludeFilters を併用する際に、コマンドクラスを含むパッケージを除外してしまう場合によくある間違いです。

アノテーションベースの登録

The @Command annotation marks a method as a candidate for command registration. In the following example, a command example is defined.

@Component
class MyCommands {

	@Command(name = "example")
	public String example() {
		return "Hello";
	}

}
The command name is optional. If it is not provided, the method name is used. When the command returns a value, it will be printed to the shell output.

Outside a Spring Boot application, use @EnableCommand on a configuration class to register the classes containing your @Command methods.

@EnableCommand({ MyCommands.class })
class App {

}
Spring Boot アプリケーションでは @EnableCommand は必要ありません。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) の処理やシェル出力へのメッセージの出力など、コマンドの作成を簡素化するユーティリティメソッドをいくつか提供します。

コマンドレジストリ

The CommandRegistry class holds the set of commands known to the Shell application. It is possible to dynamically register and unregister commands.

デフォルトでは、Spring Shell はアプリケーションコンテキストで定義されたコマンドを CommandRegistry に入力します。