If 语句取决于传递的命令行参数是什么?

If Statement dependent on what command line arugment is passed?

我的 spring-boot 应用程序可以 运行 来自 command line 并且 arguments 作为参数传递。

我想设置我的 main method,以便如果用户传递 "a" 作为参数:任务 A 是 运行。如果他们传递 "b" 作为参数,任务 B 是 运行。

我目前正在使用:

if(args.toString().contains("a")){
//run task A
}

有没有更好的方法/上面的实现是否正确?

满员class:

@Component
public class MyRunner implements CommandLineRunner {

    //other code

    @Override
    @Transactional
    public void run(String... args) throws Exception {

        if(args.toString().contains("a")){
            //run task A
        }

        if(args.toString().contains("b")){
            //run task B
        }

    }

}

args.toString 不是你想要的,它将 return 一个数组的 toString,类似于:[Ljava.lang.String;@15db9742

这更有可能是您想要的:

for(String arg : args) {
    if(arg.equals("a")) { // or .contains
        // run task A
    }
}