You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring-Shell强制使用输入别名的技术咨询

强制Spring Shell命令必须使用选项别名传参

嘿,我明白你的需求啦——就是想让fullname命令必须通过-f和-l这两个选项别名来传参,不能直接用位置参数对吧?其实这个问题很容易解决,只需要调整@ShellOption的配置就行。

问题原因

默认情况下,Spring Shell允许通过位置参数传递值,哪怕你给参数指定了选项别名。所以即使你没加-f和-l,直接传两个字符串也能匹配到firstName和lastName参数。

解决方案

给每个@ShellOption添加mode = ShellOption.OptionMode.REQUIRED属性,这个配置会强制要求必须通过选项别名(也就是-f、-l)来传递参数,不允许使用位置参数。

修改后的代码

import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

@ShellMethod("Get full Name.")
public String fullname(
        @ShellOption(value = {"-f"}, mode = ShellOption.OptionMode.REQUIRED) String firstName,
        @ShellOption(value = {"-l"}, mode = ShellOption.OptionMode.REQUIRED) String lastName
) {
    return firstName + " " + lastName;
}

效果测试

  • 当你执行合法命令:

    shell> fullname -f Nithin -l Malathesh
    

    会正常返回Nithin Malathesh。

  • 当你尝试直接传位置参数:

    shell> fullname Nithin Malathesh
    

    Spring Shell会抛出错误,提示你缺少必填的-f和-l选项,完美达到你的要求!

内容的提问来源于stack exchange,提问作者B G Nithin Malathesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:57:59