2

I d like to make a REST call once on application startup to retrieve some configuration parameters.

For example, we need to retrieve an entity called FleetConfiguration from another server. I d like to do a GET once and save the keep the data in memory for the rest of the runtime.

What s the best way of doing this in Spring? using Bean, Config annotations ..?

I found this for example : https://stackoverflow.com/a/44923402/494659

I might as well use POJOs handle the lifecycle of it myself but I am sure there s a way to do it in Spring without re-inventing the wheel.

Thanks in advance.

Orkun
  • 6,998
  • 8
  • 56
  • 103

2 Answers2

3

The following method will run once the application starts, call the remote server and return a FleetConfiguration object which will be available throughout your app. The FleetConfiguration object will be a singleton and won't change.

@Bean
@EventListener(ApplicationReadyEvent.class)
public FleetConfiguration getFleetConfiguration(){
    RestTemplate rest = new RestTemplate();
    String url = "http://remoteserver/fleetConfiguration";
    return rest.getForObject(url, FleetConfiguration.class);
}

The method should be declared in a @Configuration class or @Service class.

Ideally the call should test for the response code from the remote server and act accordingly.

Mark
  • 2,260
  • 18
  • 27
2

Better approach is to use Spring Cloud Config to externalize every application's configuration here and it can be updated at runtime for any config change so no downtime either around same.

Avis
  • 2,197
  • 18
  • 28
  • thanks! we ll consider it. in the meantime, i need to find an solution to my problem tho :) – Orkun Jun 18 '18 at 15:13
  • How about a method annotated with `@EventListener(ApplicationReadyEvent.class)` and `@Bean` that uses a Spring `RestTemplate` to make the call. – Mark Jun 18 '18 at 15:26
  • that s what i m going for now. – Orkun Jun 18 '18 at 15:33