【发布时间】:2016-06-03 19:46:57
【问题描述】:
我有一个 Spring Boot 应用程序,我需要在启动时调用一个服务(一个休息端点)。
【问题讨论】:
标签: java spring spring-boot spring-ioc
我有一个 Spring Boot 应用程序,我需要在启动时调用一个服务(一个休息端点)。
【问题讨论】:
标签: java spring spring-boot spring-ioc
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
您可以使用这个方便的界面在应用程序启动时执行任何您喜欢的任务。
要调用 REST 端点,您可以使用 RestTemplate
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://www.example.com/api/resource", String.class);
如果您使用与 JSON 响应匹配的字段构建 POJO,RestTemplate 将在 Jackson 的帮助下自动映射它们。有关详细信息,请参阅文档。
【讨论】:
我建议看一下@PostConstruct 注释。
【讨论】:
我会使用和实现ApplicationRunner
【讨论】:
您还可以将您的应用程序挂接到 ApplicationReadyEvent 或 Spring 触发的其他事件:
【讨论】: