菜单优化
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
package com.example.workutils;
|
||||
|
||||
import com.example.workutils.menu.api.MenuRunner;
|
||||
import com.example.workutils.tool.Tool;
|
||||
import com.example.workutils.tool.ToolRegistry;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.Scanner;
|
||||
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
|
||||
@Slf4j
|
||||
public class WorkUtilsApplication implements CommandLineRunner {
|
||||
|
||||
private final MenuRunner menuRunner;
|
||||
private final ToolRegistry toolRegistry;
|
||||
|
||||
public WorkUtilsApplication(MenuRunner menuRunner, ToolRegistry toolRegistry) {
|
||||
this.menuRunner = menuRunner;
|
||||
this.toolRegistry = toolRegistry;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WorkUtilsApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
if (args.length == 0) {
|
||||
showInteractiveMenu();
|
||||
} else {
|
||||
processCommand(args);
|
||||
}
|
||||
}
|
||||
|
||||
private void showInteractiveMenu() {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
menuRunner.run(scanner);
|
||||
}
|
||||
|
||||
/**
|
||||
* 命令行模式:通过ToolRegistry按命令名分发到对应Tool
|
||||
* 启动类不依赖任何具体业务Service
|
||||
*/
|
||||
private void processCommand(String... args) throws Exception {
|
||||
String command = args[0].toLowerCase();
|
||||
|
||||
Optional<Tool> toolOpt = toolRegistry.getToolByCommand(command);
|
||||
if (toolOpt.isPresent()) {
|
||||
Tool tool = toolOpt.get();
|
||||
try {
|
||||
// args[0]是命令名,从args[1]开始传给tool
|
||||
String[] toolArgs = args.length > 1 ? Arrays.copyOfRange(args, 1, args.length) : new String[0];
|
||||
tool.executeCommand(toolArgs);
|
||||
} catch (Exception e) {
|
||||
log.error("命令执行失败: {} [{}]", tool.getName(), tool.getId(), e);
|
||||
System.err.println("命令执行失败: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
System.err.println("未知命令: " + command);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user