spring-shell启动时执行命令,即通过命令行执行内置命令,非交互式执行

8 篇文章 0 订阅
5 篇文章 0 订阅

spring-shell本来支持启动时执行脚本文件的,如

java -jar my-sprint-shell.jar @/home/user/script.txt

有时候执行内容很简单,可能就一两行命令,用脚本就显得有点麻烦,所以写了一个直接执行命令的方式

添加CmdShellApplicationRunner

// 关键一步,必须在开启交互式界面执行
@Order(InteractiveShellApplicationRunner.PRECEDENCE - 101)
public class CmdShellApplicationRunner implements CommandLineRunner {

    private final Shell shell;
    private final ResultHandler<Object> resultHandler;
    private final ConfigurableEnvironment environment;

    public CmdShellApplicationRunner(Shell shell, ResultHandler<Object> resultHandler, ConfigurableEnvironment environment) {
        this.shell = shell;
        this.resultHandler = resultHandler;
        this.environment = environment;
    }

    @Override
    public void run(String... args) throws Exception {
        boolean hasCmd = false;
        List<String> commands = new ArrayList<>();
        for (String arg : args) {
            // 启动参数包含了cmd关键字,则认为后面的都是命令
            if ("cmd".equalsIgnoreCase(arg)) {
                hasCmd = true;
            } else if (hasCmd) {
                commands.add(arg);
            }
        }

        if (commands.isEmpty()) {
            return;
        }

        // 关闭交互式应用: 执行完命令直接退出应用, 不停留在交互式窗口中
        InteractiveShellApplicationRunner.disable(environment);
        final Iterator<String> iterator = commands.iterator();
        shell.run(() -> {
            if (iterator.hasNext()) {
                final String commond = iterator.next();
                return () -> commond;
            }
            return null;
        });
    }
}

配置 CmdShellApplicationRunner

配置类里将 CmdShellApplicationRunner 注册Bean

    @Bean
    public CmdShellApplicationRunner cmdShellApplicationRunner(Shell shell,
                                                               @Qualifier("main") ResultHandler<Object> resultHandler,
                                                               ConfigurableEnvironment environment){
        return new CmdShellApplicationRunner(shell, resultHandler, environment);
    }

启动程序时添加cmd参数和执行命令

java -jar my-sprint-shell.jar cmd "add 1 2" "min 1 2"

从cmd后面每一个参数都会被认为是一个执行命令,执行全部执行结束后就退出应用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值