我的spring-boot
应用程序可以从 command line
运行与 arguments
作为参数传递。
我想设置我的main method
这样,如果用户传递“a”作为参数:任务 A 就会运行。如果他们传递“b”作为参数,则运行任务 B。
我目前正在使用以下方法实现此功能:
if(args.toString().contains("a")){
//run task A
}
有没有更好的方法来做到这一点/上面的实现是否正确?
完整运行者类别:
@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
不是你想要的,它会返回一个数组的 toString,类似于:[Ljava.lang.String;@15db9742
这更有可能是您想要的:
for(String arg : args) {
if(arg.equals("a")) { // or .contains
// run task A
}
}
关于java - 如果语句依赖于传递什么命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36845545/