如何在Spring Shell中使用Kotlin传递可变参数?
Spring Shell 可变参数传递问题解决
问题场景
编写Spring Shell应用时,需要执行类似 fetch FA-207542 FA-207984 FA-211258 FA-202298 的命令,传递多个票号作为可变参数,但参数解析不符合预期。
尝试的方案及问题
方案1:使用Kotlin vararg
代码实现:
@ShellMethod(value = "fetches all pic related data for processing") fun fetch(vararg tickets: String) { println("number of tickets is ${tickets.size}") }
执行结果:
shell:>fetch FA-207542 FA-207984 FA-211258 FA-202298 number of tickets is 1
问题:所有空格分隔的参数被合并为单个字符串,导致tickets.size返回1。
方案2:使用StringArray
代码实现:
fun fetch(tickets: StringArray) { println("number of tickets is ${tickets.size()}") }
执行错误:
shell:>fetch FA-207542 FA-207984 FA-202298 Parameter specified as non-null is null: method FetchCommand.fetch, parameter tickets Details of the error have been omitted. You can use the stacktrace command to print the full stacktrace.
问题:Kotlin中不存在StringArray类型(正确应为Array<String>),且Spring Shell无法自动将多个参数绑定到数组,导致非空参数为空指针异常。
正确解决方法
Spring Shell需要通过@ShellOption注解的arity属性明确参数数量规则,结合合适的参数类型实现可变参数解析:
方式1:vararg + @ShellOption(arity = -1)
@ShellMethod(value = "fetches all pic related data for processing") fun fetch(@ShellOption(arity = -1) vararg tickets: String) { println("number of tickets is ${tickets.size}") }
arity = -1表示接受任意数量的参数,Spring Shell会将每个空格分隔的内容解析为数组的独立元素。
方式2:List<String> + @ShellOption(arity = -1)
若偏好使用集合而非数组,可采用:
@ShellMethod(value = "fetches all pic related data for processing") fun fetch(@ShellOption(arity = -1) tickets: List<String>) { println("number of tickets is ${tickets.size}") }
内容的提问来源于stack exchange,提问作者Christian Bongiorno
相关产品推荐
相关产品推荐

