SpringBoot應用程序可以通過CommandLineRunner接口來解析命令行參數。以下是一個簡單的示例:
首先,創建一個CommandLineRunner接口的實現類,并實現run方法:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public 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;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
現在,您可以在命令行中運行應用程序,并傳遞參數。例如:
java -jar my-application.jar arg1 arg2 arg3
在這個例子中,應用程序會打印出傳遞的參數:
Argument: arg1
Argument: arg2
Argument: arg3