一、起源
1.1 原由
爲什麼要使用spring shell,在公司中,發現同事使用scala 寫了一個交互的命令行程序,其實就是scala自帶的信,註冊了函數,感覺使用起來挺方便的,爲啥Java裏面沒有這樣的使用東西!挺好奇的,我想使用一個接入簡單方便,不要花費太多的時間,且我們要熟悉!最後發現spring shell 比較好!集成了spring的容器機制!這個在今天的Java 後端程序員中,要是不會spring 真的不是Java開發的感覺。因此麼事,就瞭解了一下子如何。
1.2 解決什麼問題
在使用arthas的時候,很多的命令記不住,比如arthas watch 後面需要添加一堆的參數,tarce 需要滿足規範,我只想簡單的使用,不想記住那麼多,不想慢慢的看文檔啊!因此簡單的命令行能不能解決問題?可以的,就是一個簡單的字符串處理,比如更好的給你複製到剪切板中,不是很方便?第二個需求,有些常見的命令無法記住,我想當個筆記本來使用這樣可以?哈哈 !因此寫了一個命令行的工具 https://github.com/WangJi92/wdt 武當山命令行!歡迎收藏起來~。
二、集成
1、依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell-starter</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
</dependencies>
2、簡單實現一個方法
@ShellComponent
public class MyCommands {
@ShellMethod("Add two integers together.")
public int add(int a, int b) {
return a + b;
}
}
3、運行
即可體驗
java -jar target/xxx.jar
>add 1 2
三、參考文檔
spring shell
官方文檔:https://docs.spring.io/spring-shell/docs/2.0.0.RELEASE/reference/htmlsingle/#extending-spring-shell
github spring shell:https://github.com/spring-projects/spring-shell
Jline: https://github.com/jline/jline3