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后面每一个参数都会被认为是一个执行命令,执行全部执行结束后就退出应用。