java考虑定义一个类型为“COM”的bean。实例演示。在您的配置中命令$DefaultIO
我正在尝试使用Spring boot运行此代码:
public interface DefaultIO{
public String readText();
public void write( String text);
public float readVal();
public void write( float val);
public default void uploadFile(String exit, String outputPath) {
try {
PrintWriter writer = new PrintWriter(new FileWriter(outputPath));
String line;
while ( (line = readText()) != null) {
if(line.equals(exit))
break;
if(line.equals(""))
continue;
writer.println(line);
}
writer.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public default String[] downloadFile(String outputFileName) {
try {
Scanner scanner=new Scanner(new BufferedReader(new FileReader(outputFileName)));
String str="";
while (scanner.hasNext()){
str+=scanner.nextLine()+"split";
}
scanner.close();
return str.split("split");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return "doesnt work".split(" ");
}
void close();
}
DefaultIO dio;
public Commands(DefaultIO dio) {
this.dio=dio;
}
public abstract class Command{
protected String description;
public Command(String description) {
this.description=description;
}
public abstract void execute();
}
public class mainCommand extends Command{
public mainCommand() {
super("Welcome to the Anomaly Detection Server.\n" +
"Please choose an option:\n");
}
@Override
public void execute() {
CLI cli= new CLI(dio);
cli.commands.forEach(command -> dio.write( command.description));
int clientNumber = (int) dio.readVal();
cli.commands.get(clientNumber).execute();
}
}
并从CLI类运行以下代码:
ArrayList<Command> commands;
DefaultIO dio;
Commands c;
public CLI(DefaultIO dio) {
this.dio=dio;
c=new Commands(dio);
commands=new ArrayList<>();
commands.add(c.new mainCommand());
commands.add(c.new uploadCommand());
commands.add(c.new algorithmCommand());
commands.add(c.new detectCommand());
commands.add(c.new displayCommand());
commands.add(c.new analyzeCommand());
commands.add(c.new exitCommand());
// implement
}
@GetMapping("/test")
public void start() {
// implement
commands.get(0).execute();
}
}
这是我的主要观点:
SpringApplication.run(DemoApplication.class, args);
}
private Scanner s;
@Override
public void run(String... args) throws Exception {
s = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
StandrtIO sio=new StandrtIO(s);
CLI cli=new CLI(sio);
cli.start();
s.close();
sio.close();
}
我得到了这个错误:
com中构造函数的参数0。实例演示。CLI需要类型为“com”的bean。实例演示。找不到命令$DefaultIO'
行动:
考虑定义COM类型的bean。实例演示。在您的配置中命令$DefaultIO'
# 1 楼答案
Spring试图将DeafultIO bean注入CLI构造函数
您需要用一个类实现DeafultIO接口,并用
@Component
注释该类,这将告诉Spring它是一个bean,需要在启动时初始化