SpringBoot应用程序可以通过CommandLineRunner接口来解析命令行参数。以下是一个简单的示例:
首先,创建一个CommandLineRunner接口的实现类,并实现run方法:
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;@Componentpublic class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { for (String arg : args) { System.out.println("Argument: " + arg); } }}然后,在应用程序主类中,将CommandLineRunner实现类bean注册到Spring容器中:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }}现在,您可以在命令行中运行应用程序,并传递参数。例如:
java -jar my-application.jar arg1 arg2 arg3在这个例子中,应用程序会打印出传递的参数:
Argument: arg1Argument: arg2Argument: arg3