英文:
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("${config}")
@ConfigurationProperties(prefix = "my")
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("--config")){
// convert --config to the default --spring.config.location
acceptedArgs[0] = arg.replace("--config","--spring.config.location");
}
}
SpringApplication.run(YourApp.class, acceptedArgs); // <-- use acceptedArgs
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论