2. 开始使用
要查看 Spring Shell 必须提供什么,我们可以编写一个简单的 shell 应用程序,该应用程序 有一个简单的命令来添加两个数字。
2.1. 编写一个简单的引导应用程序
从版本 2 开始,Spring Shell 已经被从头开始重写,使用了各种 考虑到增强功能,其中之一是与 Spring Boot 的轻松集成。
在本教程中,我们通过以下方式创建一个简单的 Boot 应用程序
使用 start.spring.io。这个最小的应用程序仅依赖于spring-boot-starter
并配置spring-boot-maven-plugin
要生成一个可执行的 über-jar:
<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:
<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 命令的类集)。
然后我们可以创建一个add
方法,该方法采用两个 int (a
和b
) 并返回其总和。我们需要对其进行注释
跟@ShellMethod
并在注解中提供命令的描述(唯一的
所需信息):
package com.example.demo;
@ShellComponent
public class MyCommands {
@ShellMethod("Add two integers together.")
public int add(int a, int b) {
return a + b;
}
}