以下用spring boot项目做一个示例:
这是spring boot的启动类
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
可以看到它的main方法上有参数args。
这时如果我们想在项目启动时传入参数到这个main方法,然后根据参数的不同来做相应的逻辑,以下做个传参的示例:
public class SpringbootApplication {
public static void main(String[] args) {
//打印出参数
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
SpringApplication.run(SpringbootApplication.class, args);
}
}
我用的开发工具是idea,接下来做个启动时参数设置:
点击进去修改配置 设置参数为hello world总结
要知道,main方法是给虚拟机识别并调用的,开发不能手动调用main方法,所以如果真的需要在main方法中传参数,通过以上方法也是能够做到的,当然通过 java xxx hello world 这样的命令行效果也是一样的,用这种方法做骚操作的话,还可以对启动加密,比如这样玩:
public class SpringbootApplication {
public static void main(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
//校验是不是admin的用户
if (!"admin".equals(args)) {
throw new Exception();
}
SpringApplication.run(SpringbootApplication.class, args);
}
}
启动就会报错:
综上,反正存在即合理,了解一下没问题。