08.SpringShell内置命令-新增&重写内置命令

SpringShell 的内置命令隶属于"Built-In Commands"组内, 我们也可以将自定义命令添加到此组中, 也可以重写内置命令. 需要注意的时, 新增内置命令时, 新增命令不能与内置命令名称相同; 重写内置命令时, 名称和内置命令相同且需要实现内置命令.Command接口.

1. 新增内置命令

和普通命令开发基本无异, 只需将命令所属组设置为内置命令组"Built-In Commands"即可

1.1 自定义命令echo

@ShellComponent
@ShellCommandGroup("Built-In Commands")
public class MyEcho {

    // 使用延迟注入终端
    @Lazy
    @Autowired
    private Terminal terminal;

    @ShellMethod("print line")
    public String echo(String line) {
        return line ;
    }
}

1.2 测试

shell:>help
AVAILABLE COMMANDS
Built-In Commands
        echo: print line
        exit, quit: Exit the shell.
        help: Display help about available commands.
        script: Read and execute commands from a file.
        stacktrace: Display the full stacktrace of the last error.
shell:>echo hello,shell
hello,shell

2. 替换内置命令

替换内置命令有两种方式:

  • 禁用内置命令, 再使用新增内置命令方式创建名称一样的命令
  • 集成内置命令接口, 重写内置命令

2.1 重写clear命令

  • 需要实现Clear.Command接口
  • 需要将命令添加到内置命令组"Built-In Commands"中
  • Termial 为Shell运行的终端, 使用它进行输出. 需使用延迟加载注入.
  • 笔者参考的Clear源码: org.springframework.shell.standard.commands.Clear
@ShellComponent
@ShellCommandGroup("Built-In Commands")
public class MyClear implements Clear.Command {

    // 使用延迟加载方式注入终端组件
    @Autowired
    @Lazy
    private Terminal terminal;

    @ShellMethod("my clear")
    public void clear(){
        this.terminal.puts(InfoCmp.Capability.clear_screen, new Object[0]);
        this.terminal.writer().write("clean done...\n");
    }
}

2.3 运行测试

shell:>help
AVAILABLE COMMANDS

Built-In Commands
        clear: my clear
        echo: print line
shell:>clear

clean done...
shell:>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容