温馨提示×

SpringBoot CommandLine怎样解析参数

小樊
84
2024-07-13 19:01:22
栏目: 编程语言

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

0