Spring Shell 3.1.6内置help命令自定义方案咨询
Spring Shell 自定义内置Help命令方案
问题描述
我搭建了一个Spring Shell应用,想要自定义内置的help命令输出。当前执行help help的输出如下:
shell:>help help NAME help - Display help about available commands SYNOPSIS help --command String[] --help OPTIONS --command or -C String[] The command to obtain help for. [Optional] --help or -h help for help [Optional]
期望自定义为如下样式,添加HELP区块:
shell:>help help HELP email: email@dot.com Slack: https://slckchannel NAME help - Display help about available commands SYNOPSIS help --command String[] --help OPTIONS --command or -C String[] The command to obtain help for. [Optional] --help or -h help for help [Optional]
可行解决方案
1. 自定义HelpCommand类
Spring Shell的内置Help命令由Help.Command类实现,通过继承该类并重写run方法,可直接在原有输出前插入自定义内容:
import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.commands.Help; @ShellComponent public class CustomHelpCommand extends Help.Command { private final Help help; public CustomHelpCommand(Help help) { super(help); this.help = help; } @Override @ShellMethod(key = "help", value = "Display help about available commands") public void run(String[] command) { // 输出自定义HELP区块 System.out.println("\nHELP email: email@dot.com"); System.out.println(" Slack: https://slckchannel\n"); // 调用父类方法输出原有帮助内容 super.run(command); } }
2. 排除内置HelpCommand
为确保Spring容器加载自定义命令而非内置实现,在启动类中添加排除规则:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.shell.standard.commands.Help; @SpringBootApplication @ComponentScan(excludeFilters = @ComponentScan.Filter( type = FilterType.ASSIGNABLE_TYPE, classes = Help.Command.class )) public class SpringShellApplication { public static void main(String[] args) { SpringApplication.run(SpringShellApplication.class, args); } }
3. 验证效果
启动应用后执行help help,即可看到自定义的HELP区块已添加到原有输出之前。
进阶优化(可选)
如果需要针对不同命令显示不同的HELP信息,或更精细控制输出格式,可以重写DefaultHelp类(Help接口的默认实现),自定义整个帮助信息的生成逻辑。
内容的提问来源于stack exchange,提问作者Tallen67
相关产品推荐
相关产品推荐

