如何在Spring Boot中更改配置变量名称?

huangapple go评论67阅读模式
英文:

How to change config variable names in spring boot?

问题

我正在使用 Spring Boot 构建一个独立的应用程序。我希望它能够读取用户提供的属性文件,但我想自定义命令行 API。我不想使用 --spring.config.location=...,而想使用 --config=...。Spring Boot 是否支持这种类型的定制?我该如何实现这一点?

英文:

I'm building a standalone app with spring boot. I want it read properties file provided by user but i want to customize command line API. i don't want --spring.config.location=... instead i would like --config=.... does spring boot support this kind of customization? how can i achieve this?

答案1

得分: 1

是的,可以使用--config而不是--spring.config.location=...,但这会带来一些成本。

假设配置文件位于_C:/temp/myconfig.properties_

my.message = Hello outside

使用你自己的 ConfigurationProperties

@Configuration
@PropertySource("${config}")
@ConfigurationProperties(prefix = "my")
class ApplicProps {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

然后你应该能够像这样启动应用程序:

java -jar your_application.jar --config=file:C:/temp/myconfig.properties


另一种方法是通过命令行选项参数来实现。由于--config作为一个参数传入,你可以这样启动应用程序:

public static void main(String[] args) {
	// 允许的参数
	String[] acceptedArgs = new String[1];
	for (String arg: args) {
		if(arg.startsWith("--config")){
			// 将 --config 转换为默认的 --spring.config.location
			acceptedArgs[0] = arg.replace("--config","--spring.config.location");
		}
	}

	SpringApplication.run(YourApp.class, acceptedArgs); // <-- 使用 acceptedArgs
}
英文:

Yes, it is possible to --config instead of --spring.config.location=... but it comes with a cost.

Assume C:/temp/myconfig.properties

my.message = Hello outside

Use your own ConfigurationProperties

@Configuration
@PropertySource(&quot;${config}&quot;)
@ConfigurationProperties(prefix = &quot;my&quot;)
class ApplicProps {
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

then you should be able to start your application like:

java -jar your_application.jar --config=file:C:/temp/myconfig.properties


An other way to do this is to play with the command line option arguments.
And because --config comes in as an argument you could start you application like:

public static void main(String[] args) {
		// allowed arguments
		String[] acceptedArgs = new String[1];
		for (String arg: args) {
			if(arg.startsWith(&quot;--config&quot;)){
				// convert --config to the default --spring.config.location
				acceptedArgs[0] = arg.replace(&quot;--config&quot;,&quot;--spring.config.location&quot;);
			}
		}

		SpringApplication.run(YourApp.class, acceptedArgs); // &lt;-- use acceptedArgs
	}

huangapple
  • 本文由 发表于 2020年10月20日 00:50:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64431840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定