I have to invoke an external api in multiple places within my Springboot java application. The external api will just return a static constant String value at all times.
Please find below sample code to explain better my intentions and what I wish to achieve at the end of the day
My sample code invoking external api using RestTemplate to retrieve a String value.
ResponseEntity<String> result = new RestTemplate().exchange("http://localhost:7070/api/test/{id}",
HttpMethod.GET, entity, String.class, id);
JSONObject jsonResponse = new JSONObject(result.getBody());
String reqVal = jsonResponse.getString("reqKey");
Now, My intention is to make this String globally available within the application to avoid calling this api multiple times.
I am thinking of invoking this extenal api at application startup and set this String value in Springboot application context, so that it can be retrieved from anywhere with the application.
Can anyone suggest, how can I achieve my above requirement? Or are there any other better options to think of?
Thanks in advance!
CodePudding user response:
I would store it in memory in the Spring-managed Bean that calls the external API and then allow any other Spring-managed Bean to get it from this component.
@Service
public class ThirdPartyServiceClient implements ApplicationListener<ContextRefreshedEvent> {
private String reqKey = null;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
(...)
ResponseEntity<String> result = new RestTemplate()
.exchange("http://localhost:7070/api/test/{id}", HttpMethod.GET, entity, String.class, id);
JSONObject jsonResponse = new JSONObject(result.getBody());
this.reqKey = jsonResponse.getString("reqKey");
}
public String getKey() {
return reqKey;
}
}
Now you just need to inject ThirdPartyServiceClient
Spring-managed bean in any other to be able to call getKey()
method.