Springboot application property with placeholder which is updated dynamically inside app

Viewed 327

Is there a way in which i can have a property in my application.properties file which can be holding a property with a placeholder which can later be populated inside the app?

Example (in below example {ID} is the place holder which is changed later in app):

application.properties

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

Which can then be used inside the application as below:

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

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

In above I use String class replace() function to replace {ID} with id

Are there any functionalities provided by Springboot to achieve this result where I can dynamically change a part of my property inside the app?

1 Answers

This can be achieved easily.

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

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

using the above code, if the URL has multiple placeholdets, add the values to be substituted in order.

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();   
}

Related