Spring Shell集成Groovy命令无法识别问题求助
解决Spring Shell Groovy命令无法识别的问题
问题场景
我用Groovy编写了如下Spring Shell命令类:
package com.ejemplo.prueba; import org.springframework.shell.standard.ShellComponent import org.springframework.shell.standard.ShellMethod @ShellComponent class MyShellCommands { @ShellMethod("Este es un comando de ejemplo") def myCommand() { return "¡Hola desde Groovy!" } }
依赖使用Spring Boot 3.1.4和Spring Shell 3.1.3,但执行myCommand时提示:
shell:>myCommand No command found for 'myCommand'
预期执行后返回:
¡Hola desde Groovy!
解决方案
1. 修正命令名称匹配规则
Spring Shell 3.x默认会将驼峰命名的方法名转换为**短横线分隔(kebab-case)**的命令名。你的myCommand方法对应的默认命令是my-command,尝试执行:
shell:>my-command
如果想强制使用myCommand作为命令名,可在@ShellMethod中显式指定key属性:
@ShellMethod(value = "Este es un comando de ejemplo", key = "myCommand") def myCommand() { return "¡Hola desde Groovy!" }
2. 确认组件扫描范围
确保com.ejemplo.prueba包在Spring Boot的组件扫描路径内:
- 若主应用类(带
@SpringBootApplication的类)在com.ejemplo或其父包下,组件会被自动扫描; - 若主应用类在其他包,需手动添加
@ComponentScan指定命令类所在包:
@SpringBootApplication @ComponentScan(basePackages = "com.ejemplo.prueba") public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
3. 确保Groovy类被正确编译
在Maven中添加Groovy编译插件,保证Groovy代码被正确编译并纳入Spring上下文:
<build> <plugins> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.13.1</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
4. 验证依赖配置正确性
Spring Boot 3.1.4与Spring Shell 3.1.3版本兼容,确保依赖配置完整:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.shell</groupId> <artifactId>spring-shell-starter</artifactId> <version>3.1.3</version> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>4.0.15</version> <type>pom</type> </dependency> </dependencies>
内容的提问来源于stack exchange,提问作者user2911197
相关产品推荐
相关产品推荐

