java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot使用命令行参数

SpringBoot使用命令行参数方式

作者: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));
			}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文