Reputation:
I have a @Bean which calls an external API at the start of the application. How can I have it such that it makes a new call and updates the bean on a set timer?
@Bean
public Template apiCall()
{
final String uri = "http://...";
return new RestTemplate().getForObject(uri,Template.class);
}
Upvotes: 2
Views: 3983
Reputation: 3304
One way is reload the template in some kind of factory bean.
@Component
public class TemplateProvider {
@Value("${template.uri}")
private String uri;
private Template template;
@Autowired
private RestTemplate restTemplate;
@PostConstruct
init () {
loadTemplate();
}
public synchronized void reset() {
loadTemplate();
}
public synchronized Template template() {
return template;
}
private void loadTemplate() {
try {
this.template = restTemplate.getFor...();
}
catch (Exception e) {
//
}
}
}
Then you can call reset()
inside a @scheduled
method.
The only drawback to this is that callers should not keep reference of Template
in their state.. Always access template via the provider to avoid inconsistency problems.
public class Client {
@Autowired
private TemplateProvider templateProvider;
public void method() {
templateProvider.template().method();
}
}
Upvotes: 1