带有占位符的 Springboot 应用程序属性,在应用程序内动态更新

问题描述

有没有办法让我的 application.properties 文件中的属性可以保存带有占位符的属性,该占位符稍后可以填充到应用程序中?

示例(在下面的示例中,{ID} 是稍后在应用中更改的占位符):

application.properties

url.fetch.data.with.id=http://localhost:8080/data/{ID}/details

然后可以在应用程序中使用,如下所示:

@Value("${url.fetch.data.with.id}")
String dataUrl;

String makeUrl(String id) {
  return dataUrl.replace("{ID}",id);
}

在上面我使用 String class replace() 函数{ID} 替换为 id

Springboot 是否提供了任何功能来实现这一结果,我可以在应用程序内动态更改我的部分属性

解决方法

这很容易实现。

@Value("${url.fetch.data.with.id}")
String dataUrl;

String makeUrl(String id) {
  return UriComponentsBuilder.fromHttpUrl(dataUrl).buildAndExpand(id).toString();   
}

使用上面的代码,如果URL有多个占位符,则依次添加要替换的值。

url.fetch.data.with.id=http://localhost:8080/data/{ID}/details/{detailed}?startDate={startDate}&end={endDate}
long startDate = java.time.Instant.now().toEpochMilliSeconds();
long EndDate = java.time.Instant.now().toEpochMilliSeconds();
String detailedId = "abc";

String makeUrl(String id) {
  return UriComponentsBuilder.fromHttpUrl(dataUrl).buildAndExpand(id,detailedId,startDate,EndDate).toString();   
}