一、起源
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