SpringBoot使用命令行参数方式
更新时间:2025年12月06日 09:52:49 作者:cyril 子-我
Spring Boot允许通过命令行参数灵活配置和部署项目,在main方法中传入参数并通过SpringApplication.run()加载配置,如果需要关闭命令行配置,可以设置addCommandLineProperties为false
运行SpringBoot程序时。
我们可以通过在命令行传入SpringApplication配置参数。
如 –server.port=8888, spring.profiles.active=dev 对项目进行灵活的配置和部署。
一、相关设置
通过SpringApplication.run(String… args)
中传入main方法的相关参数实现对 application 配置的加载。
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {…}
如果想要关闭相关的配置
可以通过
SpringApplication.setAddCommandLineProperties(false)
设置关闭命令行设置。
二、相关源码
调用关系:
SpringApplication.run() -> prepareEnvironment() -> configurePropertySources()
如果有
addCommandLineProperties && args.length > 0
则加载args中的相关配置。
if (this.addCommandLineProperties && args.length > 0) {
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
if (sources.contains(name)) {
PropertySource<?> source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(
new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args));
composite.addPropertySource(source);
sources.replace(name, composite);
}
else {
sources.addFirst(new SimpleCommandLinePropertySource(args));
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java利用文件输入输出流实现文件夹内所有文件拷贝到另一个文件夹
这篇文章主要介绍了Java实现文件夹内所有文件拷贝到另一个文件夹,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2018-03-03
SpringCloud Hystrix-Dashboard仪表盘的实现
这篇文章主要介绍了SpringCloud Hystrix-Dashboard仪表盘的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-08-08


最新评论