如何使用 CommandLineRunner?

要使用CommandLineRunner,我们创建一个实现CommandLineRunner接口的类,并重载它的run()方法,使用Spring如@Component之类注释此类,当Spring Boot应用启动时,就在完成启动之前,CommandLineRunner将会被执行。我们可以将命令行参数传递给 CommandLineRunner,它用于在主入口应用程序启动之前启动任何调度程序或记录任何消息。

首先,让我们看看如何在Maven运行我们的应用时传递参数,对于Spring Boot 2.x,我们可以使用-Dspring-boot.run.arguments传递参数:
mvn spring-boot:run -Dspring-boot.run.arguments=--spring.main.banner-mode=off,--customArgument=custom

如何在使用Gradle Plugin运行应用程序时传递参数? 要在build.gradle文件中配置我们的bootRun任务:


bootRun {
if (project.hasProperty('args')) {
args project.args.split(',')
}
}

现在,我们可以传递命令行参数,如下所示:
./gradlew bootRun -Pargs=--spring.main.banner-mode=off,--customArgument=custom

除了传递自定义参数,我们还可以覆盖系统属性。例如,这是我们的application.properties文件:


server.port=8081
spring.application.name=SampleApp

要覆盖server.port值,我们需要以下面的方式传递新值:
mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085

注意:
1. Spring Boot将命令行参数转换为属性,并将它们添加为环境变量;
2. 我们可以在application.properties中使用占位符,使用简短的命令行参数-port=8085,而不是多个server的-server.port=8085:


server.port=${port:8080}

2. 命令行参数优先于application.properties值

我们可以阻止我们的应用程序将命令行参数转换为属性:


@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
application.setAddCommandLineProperties(false);
application.run(args);
}
}

如何从应用程序的main()方法访问命令行参数?


@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
for(String arg:args) {
System.out.println(arg);
}
SpringApplication.run(Application.class, args);
}
}


[该贴被banq于2018-08-22 20:15修改过]