このバージョンはまだ開発中であり、まだ安定しているとは見なされていません。最新の安定バージョンについては、Spring Shell 3.4.1 を使用してください!

コマンド登録

There are two different ways to define a command, through an annotation model and through a programmatic model:

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

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

Annotation-Based Registration

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

class Example1 {

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

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

Using a @Command will not automatically register command targets, instead it is required to use @EnableCommand annotations. This model is familiar from other parts of Spring umbrella and provides better flexibility for a user being inclusive rather than exclusive for command targets.

@EnableCommand を使用してターゲットクラスを定義できます。すべての構成クラスから選択されます。

@EnableCommand({ Example1.class, Example2.class })
class App {

}
@EnableCommand is not required in a Spring Boot application, as Spring Boot auto-configuration will take care of that.

Programmatic Registration

In the programmatic model, commands can be defined as beans of type Command:

@Bean
Command myCommand() {
	return Command.builder().name("mycommand").execute(context -> {
		context.outputWriter().println("This is my command!");
	});
}

You can also use the AbstractCommand class to simplify command definitions:

@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 provides some utility methods to simplify command creation like handling help options (-h and --help) and printing messages to the shell output.