コマンドの可用性

アプリケーションの内部状態により、登録されたコマンドが必ずしも意味を成すとは限りません。例: download コマンドがあるかもしれませんが、ユーザーが リモートサーバーで connect を使用した場合にのみ機能します。これで、ユーザーが download コマンドを使用しようとすると、シェルはコマンドが存在するが、その時点では使用できないことを説明する必要があります。Spring Shell を使用すると、コマンドが使用できない理由の簡単な説明を提供することさえできます。

プログラマティック

プログラムによる登録では、AvailabilityProvider を受け取る availabilityProvider メソッドを使用できます。

private boolean connected;

@Bean
public AbstractCommand connect() {
	return org.springframework.shell.core.command.Command.builder().name("connect").execute(ctx -> {
		CommandOption connectedOption = ctx.getOptionByName("connected");
		this.connected = Boolean.parseBoolean(connectedOption.value());
	});
}

@Bean
public AbstractCommand download() {
	return org.springframework.shell.core.command.Command.builder()
		.name("download")
		.availabilityProvider(
				() -> connected ? Availability.available() : Availability.unavailable("you are not connected"))
		.execute(ctx -> {
			// do something
		});
}

アノテーション

アノテーションベースのコマンドでは、availabilityProvider 属性を使用して、使用する AvailabilityProvider Bean の名前を指定できます。

@Component
class MyCommands {

	private boolean connected;

	@Command(name = "connect")
	public void connect(String user, String password) {
		connected = true;
	}

	@Command(name = "download", availabilityProvider = "downloadAvailability")
	public void download() {
		// do something
	}

	@Bean
	public AvailabilityProvider downloadAvailability() {
		return () -> connected ? Availability.available() : Availability.unavailable("you are not connected");
	}

}

connect メソッドはサーバーへの接続に使用され(詳細は省略)、接続が完了すると connected ブール値を介してコマンドの状態が変更されます。download コマンドは、ユーザーが接続するまで使用できません。可用性プロバイダーは、2 つのファクトリメソッドのいずれかを使用して構築された Availability のインスタンスを返します。コマンドが使用できない場合は、説明を提供する必要があります。ユーザーが接続していない状態でコマンドを実行しようとすると、以下のようになります。

shell:>download
Command 'download' exists but is not currently available because you are not connected.
コマンドが利用できない理由を "because" の後に追加すると読みやすくなります。文頭に大文字を使用したり、最後にピリオドを付けたりしないでください。
Spring Shell は、コマンドの書き方やクラスの編成方法に多くの制約を課していません。ただし、関連するコマンドを同じクラスに配置することは、多くの場合良い方法であり、可用性インジケーターはそれによって恩恵を受けることができます。