Spring Boot程序可以通过实现CommandLineRunner接口,接收来自命令行的参数。
1. 创建Spring Boot应用程序
通过Spring Boot提供的工具,生成样例框架程序,不用勾选任何其它额外依赖功能。
2. 修改Application类
修改Application类,继承CommandLineRunner接口,并实现run()方法。
参考以下样例代码。
package cn.codenotes.springboot.cmdline;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootCmdLineApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootCmdLineApplication.class, args);
}
// Spring环境初始化后,调用此方法
@Override
public void run(String... args) throws Exception {
for (String argValue : args) { // 遍历参数列表中的值
System.out.println("参数值为:" + argValue);
}
}
}
3. 启动程序
在启动Spring程序时,加入命令行参数后启动。启动后参数将依次打印出来。
4. 下载代码
GitHub:https://github.com/syyzxsyf/codenotes/tree/master/SpringBootCmdLine