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:>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值