快速开始
要查看Spring Shell能提供什么功能,我们将编写一个简单的Hello World 命令行应用程序。
创建一个项目
对于这个快速教程的目的,请使用以下命令克隆并构建项目:
$>git clone [email protected]:spring-projects/spring-shell.git
$>cd spring-shell
$>./mvnw install -DskipTests
您的第一个命令
在您最喜欢的IDE中,打开org.springframework.shell.samples.helloworld.SpringShellApplication:
@EnableCommand(SpringShellApplication.class)
public class SpringShellApplication {
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringShellApplication.class);
ShellRunner runner = context.getBean(ShellRunner.class);
runner.run(args);
}
@Command(name = "hello", description = "Say hello to a given name", group = "Greetings",
help = "A command that greets the user with 'Hello ${name}!'. Usage: hello [-n | --name]=<name>")
public void sayHello(@Option(shortName = 'n', longName = "name", description = "the name of the person to greet",
defaultValue = "World") String name) {
System.out.println("Hello " + name + "!");
}
}
此类定义了一个名为hello的单一命令,该命令可接受一个可选参数name,并将问候消息打印到标准输出。
The main方法启动了一个Spring应用程序上下文并运行了控制台。要运行该应用程序,请使用以下命令执行SpringShellApplication类:
./mvnw -pl org.springframework.shell:spring-shell-sample-hello-world exec:java -Dexec.mainClass=org.springframework.shell.samples.helloworld.SpringShellApplication
这将启动Shell,并且你应该会看到一个提示符并能够像这样输入命令:
$>help
Available commands:
Built-In Commands
clear: Clear the terminal screen
help: Display help about available commands
version: Show version info
Greetings
hello: Say hello to a given name
$>hello --name=foo
Hello foo!
$>exit
Exiting the shell
恭喜,您已创建并运行了第一个Spring Shell应用程序!