2. 开始使用

要查看 Spring Shell 必须提供什么,我们可以编写一个简单的 shell 应用程序,该应用程序 有一个简单的命令来添加两个数字。spring-doc.cadn.net.cn

2.1. 编写一个简单的引导应用程序

从版本 2 开始,Spring Shell 已经被从头开始重写,使用了各种 考虑到增强功能,其中之一是与 Spring Boot 的轻松集成。spring-doc.cadn.net.cn

在本教程中,我们通过以下方式创建一个简单的 Boot 应用程序 使用 start.spring.io。这个最小的应用程序仅依赖于spring-boot-starter并配置spring-boot-maven-plugin要生成一个可执行的 über-jar:spring-doc.cadn.net.cn

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

2.2. 添加对 Spring Shell 的依赖

开始使用 Spring Shell 的最简单方法是依赖于org.springframework.shell:spring-shell-starter人工制品。 它配备了使用 Spring Shell 所需的一切,并且可以很好地与 Boot 配合使用。 根据需要仅配置必要的 bean:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.shell</groupId>
    <artifactId>spring-shell-starter</artifactId>
    <version>2.1.15</version>
</dependency>
鉴于 Spring Shell 启动了 REPL(Read-Eval-Print-Loop)因为存在此依赖项, 您需要在构建时跳过测试 (-DskipTests) 或删除示例集成测试 这是由 start.spring.io 生成的。如果不删除它,集成测试将创建 SpringApplicationContext并且,根据您的构建工具,会卡在 eval 循环中或因 NPE 而崩溃。

2.3. 您的第一个命令

现在我们可以添加第一个命令。为此,请创建一个新类(名称随你所愿)并 用@ShellComponent(的变体@Component用于限制 扫描 candidate 命令的类集)。spring-doc.cadn.net.cn

然后我们可以创建一个add方法,该方法采用两个 int (ab) 并返回其总和。我们需要对其进行注释 跟@ShellMethod并在注解中提供命令的描述(唯一的 所需信息):spring-doc.cadn.net.cn

package com.example.demo;

import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellComponent;

@ShellComponent
public class MyCommands {

    @ShellMethod("Add two integers together.")
    public int add(int a, int b) {
        return a + b;
    }
}

2.4. 试用应用程序

要构建应用程序并运行生成的 jar,请运行以下命令:spring-doc.cadn.net.cn

./mvnw clean install -DskipTests
[...]

java -jar target/demo-0.0.1-SNAPSHOT.jar
shell:>

黄色shell:>prompt 邀请您键入命令。类型add 1 2ENTER,并欣赏其中的魔力:spring-doc.cadn.net.cn

shell:>add --a 1 --b 2
3

你应该使用 shell(提示:有一个help命令)。完成后,键入exit并按ENTER.spring-doc.cadn.net.cn

本文档的其余部分将更深入地研究整个 Spring Shell 编程模型。spring-doc.cadn.net.cn