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

如何定义无值ShellOption以判断其是否存在?

在Spring Shell中实现--without-logs这类开关参数

要实现这种无值的开关参数,核心是利用布尔类型的@ShellOption,通过默认值区分用户是否传入参数。以下是具体实现步骤:

命令类实现

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

@ShellComponent
public class MyCustomCommand {

    @ShellMethod(key = "my-command", value = "自定义命令,支持禁用日志的开关")
    public String executeCommand(
            @ShellOption(value = "--without-logs", defaultValue = "false", help = "传入此参数则禁用日志输出") boolean disableLogs,
            @ShellOption(value = "--other-opts", help = "其他业务参数") String otherOptions
    ) {
        // 根据开关值执行不同逻辑
        if (disableLogs) {
            // 无日志执行分支
            return String.format("已执行命令(日志已禁用),其他参数:%s", otherOptions);
        } else {
            // 带日志执行分支
            return String.format("已执行命令(日志正常输出),其他参数:%s", otherOptions);
        }
    }
}

关键说明

  • 用布尔类型参数接收开关状态:用户不传--without-logs时,参数值为defaultValue设置的false;传入参数时,自动转为true
  • @ShellOption的value属性直接指定命令行参数名--without-logs,确保能匹配用户输入
  • 方法内部通过判断布尔值,分支处理有无日志的业务逻辑

使用示例

  • 启用无日志模式:
    my-command --without-logs --other-opts "test-data"
    
  • 保持默认日志模式:
    my-command --other-opts "test-data"
    

内容的提问来源于stack exchange,提问作者Muratcan Şentürk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:35:30